gpt4 book ai didi

ajax - 评估来自 jQuery .ajax() 的成功数据并根据结果返回 true/false

转载 作者:行者123 更新时间:2023-12-01 01:37:36 25 4
gpt4 key购买 nike

您好,stackoverflow 社区。我是一个长期潜伏者,也是第一次发帖。我花了几个小时进行研究,试图克服以下问题,但显然没有成功,因为我在这里发帖。应该指出的是,我使用 jQuery(或任何与此相关的 JS)编码才几个月。

我的目标是这样的:使用 .ajax() 提交一个简单的表单,然后如果返回的成功数据 == 'Success' 则发出警报(成功!)并返回 true(重新加载页面),或者使用以下内容填充 div错误消息,否则返回 false。

我在研究过程中尝试了许多不同的方法,但无论我尝试过什么,我都可以获得成功的评估:数据返回 true。

这是我最近的尝试:

$(document).ready(function() {

$('#error').hide();

$("#submit_result").submit(function() {
var postString = $('#submit_result').formSerialize(); /* Function from jQuery.form.js */
$.ajax({
url: 'inc/submit_speedtest.inc.php',
type:'POST',
data:postString,
success: function(msg) {
$('#error').html(msg);
},
error:function() {
$('#error').html('Error validating CLid!');
}
});
if ($('#error').html() == 'Success') {
alert('Done');
return true;
}
$('#error').show();
return false;
});
});

一切都很好,除了:

if ($('#error').html() == 'Success') {
alert('Done');
return true;
}

此测试的计算结果永远不会为 true。我尝试了很多不同的方法,包括诸如

if $("#error:contains('Success')") {

submit_speedtest.inc.php 的内容:

    <?php

session_start();

include('lib.inc.php');
restrict_unauthorized();

if(!empty( $_POST['clid'])) {
$clid = trim($_POST['clid']);
$result = check_clid($clid);
echo $result;
}else{
echo "No CLid!";
}

?>

check_clid() 函数运行一个简单的 MySQL 查询以确保 CLid 存在。如前所述,这似乎工作正常

我希望这一切都有意义,并且非常感谢 stackoverflow 社区为我提供的任何帮助。

编辑

感谢你们的意见。我能够从你们的回复中收集到有用的信息。您让我更好地了解了回调的工作原理。

这是我最终得到的 jQuery 代码:

$(document).ready(function() {

$('#status_msg').hide();

$("#submit_result").submit(function(e){
e.preventDefault();
var postString = $('#submit_result').formSerialize();
$.ajax({
url: 'inc/submit_speedtest.inc.php',
type:'POST',
data:postString,
success:function(msg) {
$('#status_msg').html(msg);
$('#status_msg').show();
},
error:function() {
$('#status_msg').html('<font color="red">Error validating CLid!</font>');
$('#status_msg').show();
}
});
});
});

PHP 完成剩下的工作,并且一切正常。

再次感谢。

最佳答案

$ajax 是异步的,因此您不能返回任何内容,您应该以不同的方式组织代码。

  $("#submit_result").submit(function(e){
e.preventDefault();
var postString = $('#submit_result').formSerialize(); 
$.ajax({
url: 'inc/submit_speedtest.inc.php',
type:'POST',
data:postString,
success: function(msg) {
$('#error').html(msg);
alert('Done');
$('#error').show();
//do whatyou need to do after you have succesfully vompleted the ajax request
},
error:function() {
$('#error').html('Error validating CLid!');
$('#error').show();
}
});

});

在你的代码中

  if $("#error:contains('Success')") 

始终为 false,因为它在调用 ajax 函数后立即执行,而不等待函数完成。您可以在 $.ajax() 调用中将 async 属性设置为 false 以使调用同步,但这违背了 ajax 的实用性

关于ajax - 评估来自 jQuery .ajax() 的成功数据并根据结果返回 true/false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9536049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com