我如何返回当前对象作为JSON字符串从内部的对象与jquery或javascript

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

本文关键字:对象 字符串 内部 JSON javascript jquery 何返回 返回      更新时间:2023-09-26

我需要一个函数将当前实例作为json文本返回,因为我将使用ajax请求将值发送到服务器端脚本。

我不知道在哪里使用"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

你可能需要在你的问题中更具体,但如果你需要在输入函数中使用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