[英]Using the response of AJAX Post
我一直在开发注册表格,但是慢慢地,当然,我一直在学习一些javascript和jquery,以进一步支持我对这一切的了解。 我遇到了一个问题,但是问题是我无法从AJAX请求获得响应。
我的AJAX请求在单独的函数中,我有多种用途。 我已将alert();放在代码中以进行调试。
function validate_input ( input, type ) {
$.ajax({
type:'post',
url: 'ajax_request.php',
data: "type=" + type + "&input=" + input,
success: function( response ) {
if( response == "true" || response == "false" ) {
alert( "working" );
console.log(response);
return response;
} else {
alert( "AJAX/jQuery Error" );
alert( "Reponse !== true or false" );
}
}
});
}
我可以确认ajax_request.php文件正确地响应了true或false ,但是,对于那些对此感兴趣的人是代码。
if (!defined('BASEPATH') &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
exit('Direct Access to this file has been disabled.');
include('core/db.php');
$validateType = intval( $_POST['type'] );
$input = escape_string( $_POST['input'] );
if( $validateType == 1 ) // validate username
{
echo ( user_exists( $input ) ? "true" : "false" );
} else if( $validateType == 2 ) // validate email
{
echo "true"; // not coded yet
}
最后,在需要时调用函数( 使用.blur() ),如下所示;
var username_value = "Jake"; // for debugging purposes, var definitely contains something
validate_input( username_value, 1 );
alert( validate_input( username_value, 1 ) ); alerts "undefined"
我只是想知道是否有人能看到导致问题的代码问题,请不要建议我使用验证器插件,这不是问题的答案。
谢谢,
Ajax调用是异步的,您不能像这样返回响应。 使用ajax,您可以定义一个回调函数,该函数在收到响应时被调用。 代码执行不会停止,而是等待响应后再继续。
因此,您需要在成功函数中做任何想做的事情,或者从那里调用另一个函数。
Ajax的“类型”设置为POST,但是您的脚本正在检查$ _GET数组中的参数。 将$ _GET更改为$ _POST或将ajax类型更改为“ get”。
alert( validate_input( username_value, 1 ) );
alerts "undefined"
这样就行不通了。 首先-您正在使用异步ajax调用。
第二:
success: function( response ) {
if( response == "true" || response == "false" ) {
alert( "working" );
console.log(response);
return response;
} else {
alert( "AJAX/jQuery Error" );
alert( "Reponse !== true or false" );
}
}
在上面的代码中,将belogns返回到成功处理程序函数,而不是validate_input
函数。 基本上,您将您的回复无处返回。
因此,而不是return response;
您应该做任何需要做的事情:
success: function( response ) {
if( response == "true" || response == "false" ) {
alert( "working" );
console.log(response);
alert(response);//here you do what you need.
} else {
alert( "AJAX/jQuery Error" );
alert( "Reponse !== true or false" );
}
}
.get
, .post
, .load
工作方式与在后面使用$.ajax
方式相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.