【问题标题】:How to get response with .load jQuery如何使用 .load jQuery 获得响应
【发布时间】:2021-09-09 10:06:43
【问题描述】:

我正在使用 jQuery 中的 .load 函数将 html 页面加载到带有 ajax 的 div 中,但我遇到了问题,因为服务器总是不发送 html,有时它会发送 json,我想得到它json.load

我认为这将是.load 中的回调函数中的response,但它返回未定义,只是将json 放入div 中,所以我怎样才能得到json.load

服务器发送这个json:

{ok : false}

这是我的 jQuery 代码:

$( "#div").load( "url", function( response, status, xhr ) {
    ////how can I get the false result here response.ok return nothing!!!
    console.log(response.ok);
    if ( status == "error" ) {
        var msg = "Sorry but there was an error: ";
        $( "#div" ).html( msg + xhr.status + " " + xhr.statusText );
    }
});

【问题讨论】:

  • 如果您只想要 JSON,为什么要使用 .load() 而不是 .get()
  • @jfriend00 因为正如我所提到的,服务器有时会发送一个 html 并且 .load 函数可以正常工作,但在某些情况下它会返回一个 josn,我想用 .load 获取那个 json
  • 为什么不使用.get(),然后你可以检查返回数据类型,如果服务器返回HTML,你可以把它放在DOM中(就像.load()一样),但如果它返回 JSON,那么您已经有了 JSON 响应。您正在发出请求并且不知道服务器将返回什么似乎有点奇怪 - 通常情况并非如此。
  • @ jfriend00 我知道服务器的响应是什么,我只是在这里设置一个条件,我只想知道有什么方法可以使用 .load(not .得到)。这是我的第一个问题,答案很简单,不是或是。如果是,如何。你要回答我的问题吗???
  • .load() 根本不是您想要用来从服务器获取 JSON 的东西。这是工作的错误工具。我的建议是使用正确的工具来完成工作,而不是尝试破解错误的工具。

标签: javascript jquery ajax json


【解决方案1】:

我认为你必须这样做:

$("#div").load( "url", function( response, status, xhr ) {
    var responseAsObject = $.parseJSON(response);
    console.log(responseAsObject.ok);
});

【讨论】:

    【解决方案2】:

    使用响应替换#div html内容:

    $("#div").load("url", function (responseTxt, statusTxt, xhr) {
        if (statusTxt == "success") {
            var responseAsObject = $.parseJSON(response);
            $(this).html( responseAsObject.response );
        }
        if (statusTxt == "error") 
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
    

    【讨论】:

    • 这对我很有用。 xhr 第三个参数是秘诀。就我而言,我从我的 Action 方法返回了一个 Task 。我只是将其更改为 Task,并返回了一个 BadRequest(message),它变成了 400 的 xhr.status。其他一切都照常工作。
    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2014-08-13
    • 2018-03-17
    • 1970-01-01
    • 2017-08-08
    相关资源
    最近更新 更多