Javascript 将jQuery ajax响应与IF语句一起使用
我使用jQueryAjax将数据发送到php。成功或失败后,php会发回响应。到目前为止一切正常。现在我的问题是如何在jquery中使用if语句来使用响应执行某些操作 见示例:Javascript 将jQuery ajax响应与IF语句一起使用,javascript,jquery,Javascript,Jquery,我使用jQueryAjax将数据发送到php。成功或失败后,php会发回响应。到目前为止一切正常。现在我的问题是如何在jquery中使用if语句来使用响应执行某些操作 见示例: $.post("php/send.php", { email:$( '#email' ).val(), name:$( '#name' ).val() }, function(response) { alert(response) // sho
$.post("php/send.php",
{
email:$( '#email' ).val(),
name:$( '#name' ).val()
},
function(response) {
alert(response) // shows "Error!"
if (response != "" || response != "Error!") {
//do A...
} else {
//do B...
}
)};
我的if语句不起作用。即使来自php的响应是“Error!”它也会//做一个。如何解决这个问题?通常用php页面的纯文本进行响应是不安全的,我建议您使用
json
进行php和ajax之间的通信,不管怎样,您的代码似乎还可以,尝试添加trim()
对于php中返回的字符串使用php页面中的纯文本进行响应通常是不安全的,我建议您使用json
进行php和ajax之间的通信,无论如何,您的代码似乎还可以,尝试添加trim()
返回php中的字符串如果send.php
的唯一输出类似于
,那么发布的代码应该可以工作,我不知道这是否是一个打字错误,但是$.post
函数的右括号应该是})代码>
方法1
好的做法是对响应使用json格式(),例如:
php
<?php
// if there is an error fill the error data
$response['error'] = 'Error message!';
// else fill the correct data
$response['data'] = [ 'foo' => 'Some data', 'bar' => 'Some other data' ];
header( 'Content-Type: application/json' );
die( json_encode( $response ) );
?>
<?php
// if case of an error
http_response_code(400);
die( 'Error message!' );
?>
方法2
或者,可以手动设置HTTP响应代码(),以便调用的fail()
方法,如下所示:
php
<?php
// if there is an error fill the error data
$response['error'] = 'Error message!';
// else fill the correct data
$response['data'] = [ 'foo' => 'Some data', 'bar' => 'Some other data' ];
header( 'Content-Type: application/json' );
die( json_encode( $response ) );
?>
<?php
// if case of an error
http_response_code(400);
die( 'Error message!' );
?>
如果send.php
的唯一输出类似于
,并且我不知道它是否是打字错误,但是$.post
函数的右括号应该是},那么发布的代码应该可以工作代码>
方法1
好的做法是对响应使用json格式(),例如:
php
<?php
// if there is an error fill the error data
$response['error'] = 'Error message!';
// else fill the correct data
$response['data'] = [ 'foo' => 'Some data', 'bar' => 'Some other data' ];
header( 'Content-Type: application/json' );
die( json_encode( $response ) );
?>
<?php
// if case of an error
http_response_code(400);
die( 'Error message!' );
?>
方法2
或者,可以手动设置HTTP响应代码(),以便调用的fail()
方法,如下所示:
php
<?php
// if there is an error fill the error data
$response['error'] = 'Error message!';
// else fill the correct data
$response['data'] = [ 'foo' => 'Some data', 'bar' => 'Some other data' ];
header( 'Content-Type: application/json' );
die( json_encode( $response ) );
?>
<?php
// if case of an error
http_response_code(400);
die( 'Error message!' );
?>
在if条件中,如果响应不是空字符串,则短路OR(即| |)左侧的表达式将返回true。当response=“Error!”即不为空时,| |的第一部分变为true,并且//do A将执行。| |右侧的表达式,在本例中为response!=当| |左侧的表达式为true时,将忽略“Error!”。在if条件中,如果响应不是空字符串,则短路或(即| |)左侧的表达式将返回true。当response=“Error!”即不为空时,| |的第一部分变为true,并且//do A将执行。| |右侧的表达式,在本例中为response!=当| |左侧的表达式为真时,“Error!”将被忽略。您的答案不正确。当回调有数据时,它将执行一个。@GuyT,好的,你是对的,我只是删除了那个部分,忘记了它,因为它没有任何意义。你的答案不正确。当回调有数据时,它将执行一个。@GuyT,好的,你是对的,我只是简单地删除并忘记了那个部分,因为它无论如何都没有意义