如何从ajax成功回调函数中读取javascript变量

时间:2016-05-12 03:40:30

标签: javascript jquery

我在做

$.ajax({
    type: "GET",
    url: url, //valid url..The ajax part works fine
    dataType: 'html',
    success: function(response) {

        if (loginStatus !== 'false') {
            testFunction(response); //assuming there is a function called testFunction
        }
    }
});

响应是html的混合内容,它还包含

<script>var loginStatus = 'false'</script>

if(loginStatus!=='false')在成功时不起作用。我做错了什么?

响应看起来像这样

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
This is a test page
<script>var loginStatus = 'false'</script>
</body>

</html>

3 个答案:

答案 0 :(得分:3)

解决方案并不漂亮。如果响应是JSON,这将更容易。 Why can't I parse a Ajax html GET response in jQuery?提供了潜在解决方案的提示。

您必须解析返回的HTML。不好的部分是Javascript部分必须是eval d(糟糕的做法!),除非你做一些正则表达式魔法得到变量的值。

更新(不要这样做):

同样,免责声明,这是不好的做法,但这是可能的。以下只是应用于您的代码的概念证明。还有JSFiddle基本想法。基本上,您使用JQuery的.parseHTML方法解析响应,并使用.globalEval评估脚本,此时变量可供检查。

$.ajax({
  type: "GET",
  url: url, //valid url..The ajax part works fine
  dataType: 'html',
  success: function(response) {
    var scriptContent = $($.parseHTML(response, document, true)).filter('script').text();
    $.globalEval(scriptContent);
    // at this point, the variable loginStatus should be defined

    if (loginStatus !== 'false') {
        testFunction(response); //assuming there is a function called testFunction
    }
  }
});

另一个参考:jQuery - script tags in the HTML are parsed out by jQuery and not executed

答案 1 :(得分:1)

我认为你无法访问ajax返回中的变量,因为它的javascript没有被解释。

这不是一个好主意(你可能会遇到其他问题),但你可以将返回隐藏的iframe并使用以下内容访问变量:

document.getElementById("iframeId").contentWindow.loginStatus

如果您控制了正在检索ajax结果的页面,我建议您只响应变量内容或json以便在javascript中轻松操作。

答案 2 :(得分:0)

$.ajax({
    type: "GET",
    url: 'loginCheck.php', //valid url..The ajax part works fine
    dataType: 'html',
    success: function(response) {
        if (response == "YES") {
         testFunction(response); //assuming there is a function called testFunction
        }
    }
});

loginCheck.php

//检查用户名和密码 如果它与数据库中的用户名和密码匹配。 然后回显“是”否则回显“否”
我使用PHP脚本语言解释了这个登录概念。