我使用上述方法和其与在URL一个参数效果很好。

e.g。 Students/getstud/1其中应用控制器/动作/参数格式。

现在我在学生控制器接受两个参数的操作,并返回一个JSON对象。

那么,如何与$.getJSON()使用post方法发布数据?

类似的方法也是可接受的。

在点是调用与AJAX的控制器的动作。

有帮助吗?

解决方案

在$ .getJSON()方法的HTTP GET和POST不。您需要使用 $。员额()

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

在这一号召,dataToBeSent可能是你想要的任何东西,但如果发送的是HTML表单的内容,你可以使用的序列方法从表单创建用于POST数据。

var dataToBeSent = $("form").serialize();

其他提示

这是我的 “一行” 溶液:

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

为了使用JSONP,和POST方法,该函数将“回调” GET参数的URL。这是使用它的方式:

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

在服务器必须准备处理回调GET参数和返回JSON字符串为:

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

其中 “jsonp000000” 是回调GET值。

在PHP实施将如:

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

我做了一些跨域测试,它似乎工作。还需要更多的测试,但。

只要这些行添加到您的<script>(jQuery是加载之后的地方,但任何发布前):

$.postJSON = function(url, data, func)
{
    $.post(url, data, func, 'json');
}

替换(部分/全部)配有$.getJSON $.postJSON和享受!

您可以使用相同的JavaScript回调函数与$.getJSON。 无需服务器端的变化。 (好吧,我总是建议在PHP中使用$_REQUEST http://php.net /manual/en/reserved.variables.request.php 在$ _REQUEST ,$ _GET和$ _POST哪一个是最快?

这比@莱佩的溶液简单。

我有在做的getJSON代码。我只是用后取而代之。令我惊讶的是,它的工作

   $.post("@Url.Action("Command")", { id: id, xml: xml })
      .done(function (response) {
           // stuff
        })
        .fail(function (jqxhr, textStatus, error) {
           // stuff
        });



    [HttpPost]
    public JsonResult Command(int id, string xml)
    {
          // stuff
    } 

我只是用柱以及如果:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

$.getJSON()是用于发送AJAX请求和取回JSON数据作为响应非常方便。唉,jQuery的文档缺乏应该被命名$.postJSON()一姐功能。为什么不直接使用$.getJSON(),并用它做什么?嗯,也许你想发送大量数据,或在我的情况下,IE7只是不希望与一个GET请求正常工作。

这是真的,目前还没有$.postJSON()方法,但可以通过在$.post()功能指定的第四参数(型)完成同样的事情:

我的代码看起来是这样的:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');

如果你只有两个参数,你可以这样做:

$.getJSON('/url-you-are-posting-to',data,function(result){

    //do something useful with returned result//
    result.variable-in-result;
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top