How to use getJSON, sending data with post method?

后端 未结 7 999
暗喜
暗喜 2020-11-29 17:45

I am using above method & it works well with one parameter in URL.

e.g. Students/getstud/1 where controller/action/parameter format is applied.

相关标签:
7条回答
  • 2020-11-29 18:41

    This is my "one-line" solution:

    $.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }
    

    In order to use jsonp, and POST method, this function adds the "callback" GET parameter to the URL. This is the way to use it:

    $.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
       console.log(data.name);
    });
    

    The server must be prepared to handle the callback GET parameter and return the json string as:

    jsonp000000 ({"name":"John", "age": 25});
    

    in which "jsonp000000" is the callback GET value.

    In PHP the implementation would be like:

    print_r($_GET['callback']."(".json_encode($myarr).");");
    

    I made some cross-domain tests and it seems to work. Still need more testing though.

    0 讨论(0)
提交回复
热议问题