Why is this jQuery ajax failing?
I'm trying to do some really basic AJAX using PHP & jQuery, but for some reason when I enter text into the input field and click the button I'm always getting null data back. What am I doing wrong?
WebService.php:
<?php
$return['ReturnString'] = $_POST['SearchString'];
for ($i = 1; $i < 100; $i++)
{
$return['ReturnString'] = $return['ReturnString'] . $_POST['SearchString'];
}
return json_encode($return);
?>
HTML:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript" src="Scripts/script.js"></script>
</head>
<body>
<form>
<div>
<input type="text" id="txtJavaPHP" />
<input type="button" id="btnJavaPHP" value="Go" />
<br />
<br />
<span id="spanJavaPHP"></span>
</div>
</form>
</body开发者_运维知识库>
</html>
Script.js:
$(document).ready(SetupButtonClicks);
function SetupButtonClicks() {$('#btnJavaPHP').click(DoPHP);}
function DoPHP() {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'WebService.php',
dataType: 'json',
data: {
SearchString: $('#txtJavaPHP').val()
},
success: function (data) {
if (data == null)
$('#spanJavaPHP').text("Data is null");
else
$('#spanJavaPHP').text(data.ReturnString);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#spanJavaPHP').text('There was an error: ' + errorThrown);
}
});
return false;
}
I think the problem lies here, but I have not used AJAX for a while, so I was not able to fully go through the AJAX Code:
echo $return['ReturnString']; return json_encode($return);
You should be echoing the json_encode($return);
echo json_encode($return);
This should hopefully fix it. Although I do not know why you are looping that data 100 times...but yea.
精彩评论