我在做
$.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>
最佳答案
解决方案并不完美。如果响应是 JSON,这会容易得多。 Why can't I parse a Ajax html GET response in jQuery?提供潜在解决方案的提示。
您必须解析返回的 HTML。不好的部分是,Javascript 部分必须进行 eval(不好的做法!),除非您执行一些正则表达式魔法来获取变量的值。
更新(不要这样做):
再次声明,这是不好的做法,但这是可能的。以下只是应用于您的代码的概念证明。还有一个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
关于javascript - 如何从ajax成功回调函数中读取javascript变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176849/