如何使用 .load jQuery 获得响应 [英] How to get response with .load jQuery

查看:27
本文介绍了如何使用 .load jQuery 获得响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working with .load function in jQuery to load a html page into a div with ajax but I have problem since server always doesn't send a html, sometimes it send a json and I want to get that json with .load.

我认为它是 .load 回调函数中的 response 但它返回 undefined 并将该 json 放入 div 所以我怎样才能用 .load 得到那个 json.

I thought it would be a response in callback function in .load but it return undefined and just put that json into the div so how can I get that json with .load.

服务器发送这个json:

The server send this json :

{ok : false}

这是我的 jQuery 代码:

Here is my jQuery code:

$( "#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 );
    }
});

推荐答案

我认为你必须这样做:

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

这篇关于如何使用 .load jQuery 获得响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆