【发布时间】:2015-06-25 08:08:30
【问题描述】:
我正在尝试让 ajax 读取并将 php 文件的回显发布到搜索建议框中,但它似乎不起作用。有什么建议哪里出错了?
(代码更新为没有简单错误,但仍然没有给出想要的结果)
$(document).ready(function(){
var left = $('#start').position().left;
var top = $('#start').position().top;
var width = $('#start').width();
$("#suggestionbox").css("left", left+40).css("top", top+60).css("width", width);
$("#start").keyup(function(){
var value = $("#start").val();
if(value != ''){
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {value: value},
dataType: 'html',
success: function(data) {
debugger;
$("#suggestionbox").html(data);
alert(data);
}, //success
error: function(){
alert("nothing");
} //error
}); //$.post
} //if
}); //keyup
}); //ready
php
<?php echo 'Working!'; ?>
html文件中的form和div
<form class="inputForm" action="#">
<fieldset>
<input name='start' id="start" class="inputStart" type="text" placeholder="Start" onfocus="(this.value == 'Start') && (this.value = '')" onblur="if (this.value == '') {this.value = 'Start';}" onfocus="if (this.value == 'Start') {this.value = '';}" />
<input name='end' id="End" class="inputFinish" type="text" placeholder="End" onfocus="(this.value == 'End') && (this.value = '')" onblur="if (this.value == '') {this.value = 'End';}" />
<select name="count">
<option value="1">1</option>
</select>
<input class="inputDate" type="text" data-type="date" id="datepicker" value="date" />
<input class="searchbutton" type="submit" value=" " />
</fieldset>
</form>
<div id="suggestionbox">
</div>
注意:php文件和js在同一个文件夹中。
更新:
$("#start").keyup(function(){
var value = $("#start").val();
if(value != ''){
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {value: value},
dataType: 'html',
success: function(data) {
debugger;
$("#suggestionbox").html(data);
alert(data);
}, //success
error: function(){
alert('error');
} //error
}); //$.ajax
} //if
}); //keyup
上面显示(修复)的代码没有在#suggestionbox 字段中添加任何内容,并且警报输出是 php 文件的完整代码:
<?php
echo 'Working!';
?>
【问题讨论】:
-
它不起作用,因为您尝试了准备好文档。在文档 .ready 之后写入 $('.searchbutton').click(function(){ 并将所有代码包装在其中。然后单击按钮尝试。
-
您也错过了 ajax 调用中的 dataType:html
-
2 个其他拼写错误:在 Ajax 调用中应该是 type: 'POST',在你的日期输入中应该是 data-type="date"
标签: php jquery ajax forms echo