开发者

Sending JSON data to PHP with jQuery

I'm trying to write a jQuery function to send a query string to a PHP script, but I can't seem to get the text to get to the server in the correct format. I want to send this query string (with the appropriate URL encoding):

data={"name":"Chris"}

where 'data' is always a JSON string. Using jQuery's .ajax function I tried setting my data variable to

data: { 'data': {"name":"chris"} },

but PHP ends 开发者_运维技巧up getting:

data[name]=chris

What's the proper way to send the data back to the server so that the JSON string is properly reserved, without having to hand-craft the string?


First, you'll need to use json2.js because jQuery does not include the capability to output JSON, only to parse it, and the method we will be using is not supported in IE 6/7. Convert your JavaScript object to JSON:

var encoded = JSON.stringify(data);

Then you need to include that JSON-formatted string as request data:

$.getJSON(url, {data: encoded}, function() { ... });

Edit: An older version of this post referred to the jquery-json plugin, but it's obvious that that plug-in was written when jQuery 1.3.x was current.


All you have to do is put quotes around the string

data: { 'data': '{"name":"chris"}' }


Although, unclear from your question, if you are trying to know how to handle JSON strings properly in PHP, the best way would be to use the functions json_encode and json_decode.


This is wrong:

data: { 'data': {"name":"chris"} },

You get a indexed array with key of name and value of chris.

this is right:

{ name : "chris" } 

If you want in php:

 name = "chris"; 

Then you must send

 { name : "chris" } 

Depending on if you GET you can get:

$name = $_GET["name"]; 

echo $name; // chris
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜