我执行ajax查询来检查mysql数据库中的汽车名称,如果找到汽车,它将返回“汽车名称不可用”,否则返回“汽车名称可用”。将此文本放入ID为“ checkname”的div中。
所有这些都运行良好,但是当汽车名称不可用时,当我尝试隐藏添加按钮时,它无法这样做,我也不知道为什么:/
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
}
});
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
参考方案
任何依赖于AJAX请求的响应的代码都必须在该请求的回调中调用。
function check_name() {
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function (html) {
$("#checkname").html(html);
// I placed your code here instead.
// Of course you wouldn't need to set and then get the HTML,
// since you could just do a direct comparison.
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml == compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
原因是默认情况下,AJAX请求是异步的,这意味着请求后的代码将立即执行,而不是等待响应返回。
比较HTML时要记住的另一个可能的问题是空格。如果要进行字符串比较,则必须完全相同,因此,如果有空格,则需要先对其进行修剪。您可以使用jQuery.trim()
(docs)来执行此操作。
JavaScript文件:$.ajax({ type: "POST", url: "ajax.php", data: dataString, success: function(r) { $("#div").html(r); } }); 我想在成功的情况下将页面重定向到new.php,所以在我使用a…
jQuery ajax()返回json对象,但未正确警告 - php为什么无法使用data [0] .id返回ID? $(document).ready(function(){ $.ajax({ type: 'POST', dataType: "json", url: '<?php echo matry::base_to('tests/map_it'…
jQuery Ajax PHP只工作一次 - php我有以下jQuery $("button#submit").click(function(){ $.ajax({ type: "POST", url: "process.php", data: $('form.contact').serialize(), success: fun…
jQuery-找不到Ajax网址 - php好的,我敢肯定这确实很容易,而且我很愚蠢,但是似乎并不能深入了解它。我试图从我的js文件“ custom.js”中对“ helpers.php”中的某些代码进行简单的AJAX调用。但是,我仍然收到404错误,因为我似乎并没有正确遍历文件夹,尽管我确信我正在...我的文件夹结构如下:html index.php js/ custom.js includes h…
jQuery Ajax和php类 - php我正在尝试学习如何在php中使用oop。我对jQuery也很陌生。是否可以向php类方法发出Ajax请求?我只将Ajax请求发送到专门用于此目的的文件,并且返回我需要的数据。 参考方案 简短答案:不可以。长答案:Ajax只是一个使用JavaScript从浏览器发出HTTP请求而无需离开页面的术语。您唯一可以“呼叫”的是URL。您可以编写PHP以根据URL来执…