[英]AJAX GET request not working
I am trying to make an AJAX call, it's the very first time I use AJAX, my code is the following: 我正在尝试进行AJAX调用,这是我第一次使用AJAX,我的代码如下:
$.get( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
});
vaidate.php: vaidate.php:
<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>
If I access my validate.php, I get "undefined index" error. 如果我访问validate.php,则会收到“未定义索引”错误。 What is the proper way to do this?
正确的方法是什么?
The php looks fine once you comment out the test code: 一旦注释掉测试代码,php看起来就很好了:
<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>
you need to specify that you expect JSON, the simplest way would be to use getJSON 您需要指定您希望使用JSON,最简单的方法是使用getJSON
$.getJSON( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
});
Other alternative with jQuery is jQuery的其他替代方法是
$.get( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
},"json");
or to set the contentType header in php: 或在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 }' );
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.