开发者

Javascript Create JSON Hash Array for jQuery AJAX

I am desperately trying to manually create a JSON-style array in Javascript to send over the network via jQuery's AJAX method.

var fieldsobj = {fields:[]}
$(".fact_field", fact).each(function(index, field){
    var index  = $(field).attr("data-index");
 开发者_Python百科   var name  = $(".fact_field_label", field).text().trim();
    var value  = $(".fact_field_value", field).text().trim();
    fieldsobj["fields"].push({index:index, name:name, value:value});
});
//...
$.ajax({
    type: 'PUT',
    url: url,
    data: fieldsobj,
    success: function(data){...
    },
    complete: function(){...
    }
});

What I want is the following:

{fields => [{index:0, name:1, value:2},{...},{...}]}

What I get is this:

 {"fields"=>{"0"=>{...}, "1"=>{..}, "2"=>{...}, "3"=>{...}}

What am I doing wrong?


When you pass an object as the data property, jQuery will pass it as url-encoded form parameters (e.g. foo=bar&moo=too) in the body. I think what you want is to pass JSON through the body.

Grab the json2.js written by uncle Crockford and use JSON.stringify (that library provides the functionality for browsers that still don't support it):

$.ajax({
    type: 'PUT',
    url: url,
    data: JSON.stringify(fieldsobj),
    contentType: "application/json",
    success: function(data){...
    },
    complete: function(){...
    }
});

And don't forget to set the contentType property! On the PHP side, you can use json_decode to decode the raw body content:

$fieldsobj = json_decode(@file_get_contents('php://input'));


May be this helps.

<ul>
    <li id="p1" data-age="40">John</li>
    <li id="p2" data-age="28">Jack</li>
    <li id="p3" data-age="50">Nash</li>
</ul>

<script>
var a = [];
$("li").each(function(i){
    var o = {};
    o.id = $(this).attr("id");
    o.age = $(this).attr("data-age");
    o.name = $(this).text();
    a.push(o);
});
console.log(a);
//var a = [{id:"p1",age:40, name:"John"},{id:"p2",age:28, name:"Jack"},{id:"p3",age:50, name:"Nash"}];
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜