简体   繁体   中英

Building a JSON string using javascript/jQuery

I'm using the $.post() function from jQuery to make a Ajax call with a JSON string. The call looks like this:

$.post(
    urlVar,
    jsonVar,
    function(data){
        //do stuff
    },
    'json'
)
.complete(function(){
    //do other stuff
});

To create jsonVar I'm using this code

var1 = {};
var1.id = fooId;
var1.amount = fooAmount;
var1.zoom = fooZoom;
jsonVar = JSON.stringify(var1);

To make the call work, jsonVar should look like this

{id:fooId, amount:fooAmount, zoom:fooZoom}

but it looks like this

{"id":fooId, "amount":fooAmount, "zoom":fooZoom}

Now my code will not work, because of the double quotes. I couldn't figure out how to get rid of those. Can anyone help me out?

IMPORTANT:

the code does work if I put the $.post() function like this:

$.post(
    urlVar,
    {id: fooId, amount: fooAmount, zoom: fooZoom},
    function(data){
        //do stuff
    },
    'json'
)
.complete(function(){
    //do other stuff
});

The JSON specification states that the keys must have double-quotes.

What do you mean your code won't work because of double quotes? Parse the JSON back into an object using JSON.parse ; which is built-in to many modern browsers or you can shim it using the json2 library.

Given this code:

var fooId = 'foodyfood';
var fooAmount = 10.20;
var fooZoom = 'zoomer';
var var2 = {};

var var1 = {}; 
var1.id = fooId; 
var1.amount = fooAmount; 
var2.zoom = fooZoom; 
jsonVar = JSON.stringify(var1); 
$('#showme').text(jsonVar);

the value shown in the showme would be:

{"id":"foodyfood","amount":10.2}

so your example appears to be flawed and actually is not JSON standard which specifies the double quotes.

EDIT: now your use of the post is the equivelent of:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

except that it handles the object as objects in your second example after your edit.

see the example in the documentation here: http://api.jquery.com/jQuery.post/

with this form:

$.post("test.php", { name: "John", time: "2pm" },   function(data) {
     alert("Data Loaded: " + data);   
});

so if you have:

var mytest =  { name: "John", time: "2pm" };

it becomes: on the stringify

{"name":"John","time":"2pm"}

see working example here: http://jsfiddle.net/v4NHv/

Change the post call like this

$.post(
    urlVar,
    {var1:jsonVar},
    function(data){
      //do stuff
   },
   'json'
)
.complete(function(){
   //do other stuff
});

And then of course you will need to make a little tweek to your receiving app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM