簡體   English   中英

如何使用jquery或javascript從對象內部將當前對象作為JSON字符串返回?

[英]How can I return the current object as a JSON string from inside the object with jquery or javascript?

我需要一個函數將當前實例作為json文本返回,因為我將帶有ajax請求的值發送到服務器端腳本。

我不知道在jquery選擇器中何處使用“this”關鍵字

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支持,因此您可以在不包含JSON2.js的情況下使用JSON.stringify

您可能需要在您的問題中更具體,但如果您需要在輸入函數中將其作為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM