2011-12-06 25 views
3

我需要一個函數來返回當前實例作爲json文本,因爲我將發送帶有ajax請求的值到服務器端腳本。如何使用jquery或javascript將對象當作JSON字符串從對象中返回?

我不知道在哪裏可以使用「this」關鍵字在jQuery選擇

function Actor(){ 
this.input=function(pname,ppassword){ 
    this.name=pname; 
    this.password=ppassword; 
} 
    //I need a function to return the current instance as a json text here 
    //I will send the values with an ajax request to server side script with a function 
} 

我發現,jQuery的不支持編碼爲JSON,我需要使用JSON2。 js用於序列化爲JSON字符串。

新的瀏覽器都有原生JSON支持,所以你可以使用JSON.stringify不包括JSON2.js

+0

*「我不知道在哪裏我們e jquery選擇器中的「this」關鍵字「*這與您的問題有什麼關係? jQuery選擇器如何與「Actor」實例相關? –

+0

我還是不明白。您提供的代碼中沒有任何內容與jQuery有關。 –

+0

我放棄了,你真的應該更好地解釋你的問題... –

回答

2

你可能需要在你的問題更具體,但如果你需要這個輸入函數是JSON字符串,你可以使用:

function Actor(){ 
    this.input=function(pname,ppassword){ 
     this.name=pname; 
     this.password=ppassword; 
     return JSON.stringify(this);//this will return pname and ppassword in json object string 
    } 
} 

看到這裏的JSON庫不支持原生JSON對象舊的瀏覽器:https://github.com/douglascrockford/JSON-js

相關問題