【问题标题】:How to use getJSON, sending data with post method?如何使用getJSON,用post方法发送数据?
【发布时间】:2010-10-19 13:40:20
【问题描述】:

我正在使用上述方法,它可以很好地与 URL 中的一个参数一起使用。

例如Students/getstud/1 应用了控制器/动作/参数格式。

现在我在 Students 控制器中有一个动作,它接受两个参数并返回一个 JSON 对象。

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

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

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

【问题讨论】:

  • get in getJSON 表示 使用 GET 获取一些 json。
  • @Majid Fouladpour 当我问这个问题时,我并不知道......!

标签: jquery asp.net-mvc post http-post getjson


【解决方案1】:

$.getJSON() 方法执行 HTTP GET 而不是 POST。你需要使用$.post()

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

在该调用中,dataToBeSent 可以是您想要的任何内容,但如果要发送 html 表单的内容,您可以使用 serialize 方法从您的表单中为 POST 创建数据。

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

【讨论】:

  • 只是想添加 $.getJSON 支持 Jsonp(跨域访问) 不幸的是 $.post 没有。
  • 其实.getJSON()支持跨域访问有两种方式。 JSONP,不使用 GET 或 POST,而是使用脚本注入;而且 CORS - 和 .post() 也支持 CORS。但是 CORS 要求服务器也支持它,而 JSONP 不支持。
  • 不正确,JSONP还需要服务器支持才能解析回调参数。
  • 当我使用上述函数时,我收到的是一个字符串对象而不是一个 json 对象。
【解决方案2】:

这是我的“单行”解决方案:

$.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).");");

我做了一些跨域测试,它似乎有效。不过还需要更多的测试。

【讨论】:

  • 这永远不会绕过 GET 的限制,而 POST 的最大大小可以重新定义。
  • 为什么加?callback?在网址中?这使得回调不会被我调用。我还添加了JSON.stringify(data)。 +1,有用的帖子!
  • @IonicăBizău:谢谢。为了返回一个对象,我们需要在 URL 中添加“回调”参数,并且服务器需要返回由 JQuery 生成的相同的对象名称。我还为 getJSON() 使用了一个覆盖函数:jQuery.getJSON = function(url, data, func) { return $.get(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }
【解决方案3】:

只需将这些行添加到您的<script>(在加载 jQuery 之后但在发布任何内容之前):

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

将(部分/全部)$.getJSON 替换为 $.postJSON 并享受吧!

您可以使用与$.getJSON 相同的Javascript 回调函数。 无需更改服务器端。 (好吧,我总是建议在 PHP 中使用$_REQUESThttp://php.net/manual/en/reserved.variables.request.phpAmong $_REQUEST, $_GET and $_POST which one is the fastest?

这比@lepe 的解决方案简单。

【讨论】:

  • 这不适用于通常可以应用于 getJSON 的 done() 和 fail() 方法。
【解决方案4】:

我有执行 getJSON 的代码。我只是用post替换它。令我惊讶的是,它奏效了

   $.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
    } 

【讨论】:

    【解决方案5】:

    我只是使用了 post 和 if:

    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!");
        });
    

    【讨论】:

      【解决方案6】:

      $.getJSON() 对于发送 AJAX 请求和获取 JSON 数据作为响应非常方便。唉,jQuery 文档缺少一个应该命名为$.postJSON() 的姊妹函数。为什么不直接使用$.getJSON() 并完成它呢?好吧,也许您想发送大量数据,或者就我而言,IE7 只是不想与 GET 请求一起正常工作。

      确实,目前还没有$.postJSON()方法,但是你可以通过在$.post()函数中指定第四个参数(类型)来完成同样的事情:

      我的代码如下所示:

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

      【讨论】:

        【解决方案7】:

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

        $.getJSON('/url-you-are-posting-to',data,function(result){
        
            //do something useful with returned result//
            result.variable-in-result;
        });
        

        【讨论】:

        • 我认为这不是问题的答案。
        猜你喜欢
        • 2014-07-19
        • 2012-09-10
        • 2012-11-20
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多