开发者

jquery $.post second argument. - json or query string?

$.post('somescript.php', { data: $('#myInputField').val() },
    function(replyData) {

1) Is the second argument of this $.post method - in json?

OR

2) Is the sec开发者_如何学编程ond argument of this $.post method a query string?

Thanks in advance, MEM

Note: If this question doesn't make sense, please, knowing why (it doesn't make sense) may also help and, be taken as an valid answer as well.


In general both ways are in practice very close. The function $.post or $.ajax will encode the data posted in the same way. If you want to post JSON data you should additionally encode the data value with some JSON encoder. See How do I build a JSON object to send to an AJAX WebService? as an example ($.post is a short form of $.ajax, so all which described with $.ajax and correct also for $.post)

$.post('somescript.php', { data: JSON.stringify($('#myInputField').val()) }, ...);

In the code above I use JSON.stringify from http://www.json.org/js.html.

UPDATED: After your questions in the comment I hope I understand more which you want to know. So jQuery.post don't makes any JSON encoding of data for you for and input parameters (the second parameter of jQuery.post). So it send the data always exactly in the same way. You can add additional "json" parameter (the last dataType parameter) to the $.post call, but this will not change how the data will be encoded.

The question "should I send JSON data to the server or not?" is independent on $.post and you should answer on the question yourself depend on the requirement existing in your project. Sometime it is the question of the architecture of your solution. Sometime you have to choose one special way.

In case of Microsoft ASMX Web Service for example there exist some important restriction. For example you want to deliver JSON data from the web service to be able to work easy with the data in JavaScript. So you want to have a method on the server side which have some input parameters and returns JSON as output. In case ASMX Web Service you must sent all input parameter to the web service method as JSON encoded data to be able to return JSON data from the web service, but ASMX Web Service decode/encode the data for you and you don't need manually encode/decode JSON on the server side.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜