Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php AJAX获取请求不工作_Php_Javascript_Jquery_Ajax_Get - Fatal编程技术网

Php AJAX获取请求不工作

Php AJAX获取请求不工作,php,javascript,jquery,ajax,get,Php,Javascript,Jquery,Ajax,Get,我正在尝试调用AJAX,这是我第一次使用AJAX,我的代码如下: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches" ); }); vaidate.php: <?php $user_input=$_GET['userinput']; //print_r(

我正在尝试调用AJAX,这是我第一次使用AJAX,我的代码如下:

$.get( "validate.php", { 'userinput':'x'}, function(response) {
    if( response.status ) alert( "Matches found" );
    else alert( "No matches" );
});
vaidate.php:

<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>

一旦您注释掉测试代码,php看起来很好:

<?php
  $user_input=$_GET['userinput'];
  //print_r($user_input);
  if(!is_null($user_input)) exit( '{ "status": true }' );
  else exit( '{ "status": false }' );
?>
jQuery的另一种选择是

$.get( "validate.php", { 'userinput':'x'}, function(response) {
    if( response.status ) alert( "Matches found" );
    else alert( "No matches" );
},"json");
或在php中设置contentType标头:

<?php
  $user_input=$_GET['userinput'];
  //print_r($user_input);
  header('Content-type: application/json');
  if(!is_null($user_input)) exit( '{ "status": true }' );
  else exit( '{ "status": false }' );
?>

例如,
print\r($user\u input)才能正确解析返回,但是首先需要修复未定义的索引errorSyntax有点不正确-您不需要最后一个
}
是的,它在代码中被注释了,抱歉。只有在我测试它的时候,您才应该使用getJSON,因为您的php正在返回JSON。至于未定义的索引,我不知道你为什么会得到它,除非你直接尝试时没有通过?userinput=x。你是说访问,就像在浏览器中打开validate.php一样。在这种情况下,是的,这将给您一个未定义的索引错误。其他选项是将“json”作为第四个参数传递给
$.get()
,或者将响应的
内容类型设置为“application/json”。虽然我同意这是最好的setup@itachi也许从性能角度考虑,但是如果您不需要更改任何默认选项,并且如果性能是一个问题,那么使用快捷方式要简单得多,
$。ajax
vs
$。get
不会成为您的瓶颈。@KevinB性能明智的选择将是微观优化,这是所有问题的根源。我之所以说它更好,是因为
ajax()
为您提供了对流程的更多控制。对,但如果您不需要更多控制怎么办?我的意思是这没关系。其中一个并不比另一个“更好”,它们各有各的位置。
<?php
  $user_input=$_GET['userinput'];
  //print_r($user_input);
  header('Content-type: application/json');
  if(!is_null($user_input)) exit( '{ "status": true }' );
  else exit( '{ "status": false }' );
?>