-1 javascript php jquery
我一直在疯狂试图解决这个问题.我有一个PHP脚本返回true/false,标题设置为Content-Type:text/plain.
当我使用像这样的简单.get:
$.get("ip.php");
Run Code Online (Sandbox Code Playgroud)
我可以在firebug中看到调用和加载的数据.
但是,当我尝试添加更多复杂性时,我得到"SyntaxError:syntaxerror".这是我正在使用的jquery:
var hello;
$.get('ip.php', function(data){
hello = data;
console.log(hello);
});
if (hello == "false") {
$( "#status").removeclass("working").addClass("notworking");
$(".stat").html("<li class="title">STATUS: NOT WORKING</li>");
} else {
$(".stat").html("<li class="title">STATUS: WORKING</li>");
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?在此先感谢您的帮助.
这是因为AJAX调用是异步的 - 在jQuery实际从服务器接收响应并更新hello变量之前评估条件语句.
因此,解决方案是将条件语句移动到成功回调中$.get().
p/s:另外,你没有.html()正确地转义字符串.要么使用\"逃脱双引号,或者使用单引号,即'.
var hello;
$.get('ip.php', function(data){
hello = data;
if (hello == "false") {
$( "#status").removeclass("working").addClass("notworking");
$(".stat").html("<li class=\"title\">STATUS: NOT WORKING</li>");
} else {
$(".stat").html("<li class=\"title\">STATUS: WORKING</li>");
}
});
Run Code Online (Sandbox Code Playgroud)
更妙的是:使用延迟的对象,而不是像.done(),.fail(),.always()和等(只要你认为合适).它们提供了更好的多功能性,允许您在代码中的任何位置检查AJAX调用的状态:
var ip = $.get('ip.php'); /* Make GET request */
/* Deferred object */
ip.done(function(data){
if (data == "false") {
$( "#status").removeclass("working").addClass("notworking");
$(".stat").html("<li class=\"title\">STATUS: NOT WORKING</li>");
} else {
$(".stat").html("<li class=\"title\">STATUS: WORKING</li>");
}
}).fail(function(jqXHR, textStatus, errorThrown){
// Optional
// console.log('.get failed ' + textStatus + ' ' + errorThrown);
}).always(function(){
// Optional
// console.log('$.get completed regardless of status');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
789 次 |
| 最近记录: |