$.post 工作正常,但 $.ajax 给出错误:“不应该直接访问此脚本!”
我正在使用 jQuery 库编写自动建议/自动完成脚本。当您输入 ajax 时,通过 php 文件从数据库中获取数据并向用户提供建议。
问题1: 现在,由于 $.post 请求工作正常:
/*this works*/
$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data){
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
});
$.ajax 替代方案给出以下错误: 不应该直接访问此脚本!
这是代码输出错误:
$.ajax({
type: "POST",
url: "autosuggest.php",
data: {data: ""+inputString+""},
success: callback
});
function callback(data) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
};
问题2: $.post 还有另一个奇怪的事情,回调函数需要在括号内声明:
//this works
$.post( url, params, function callback(data) {
$("div").html(data);
}
如果我在外面声明回调函数,它将不起作用:
//this won't work
$.post( url, params, callback(data));
function callback(data)
{
$("div").html(data);
}
I am working at an autosuggest/autocomplete script using jQuery library. As you type in ajax fetch the data through a php file from a database and offers suggestions to the user.
Issue1:
Now as the $.post request works fine:
/*this works*/
$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data){
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
});
the $.ajax alternative give me the following error: there should be no direct access to this script!
Here is the code that outputs the error:
$.ajax({
type: "POST",
url: "autosuggest.php",
data: {data: ""+inputString+""},
success: callback
});
function callback(data) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
};
Issue2:
There's another weird thing with $.post, the callback functions needs to be declare inside the parantheses:
//this works
$.post( url, params, function callback(data) {
$("div").html(data);
}
if I declare the callback function outside it won't work:
//this won't work
$.post( url, params, callback(data));
function callback(data)
{
$("div").html(data);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于您的第一点:该错误可能是由于您对参数的命名不同所致:
queryString
与data
。除此之外,这两个调用完全相同,事实上,$.post
内部使用$.ajax
进行调用。关于你的第二点:这并不奇怪,你在做两件不同的事情。首先,您将一个函数传递给
$.post
。在第二个中,您调用回调
并将其返回值传递给$.post
(即>未定义
)。你必须这样做:$.post(url, params,callback);
。Regarding your first point: The error might be due to you naming the parameter differently:
queryString
vsdata
. Apart from that, both calls are exactly the same and in fact,$.post
internally uses$.ajax
to make the call.Regarding your second point: That is not weird, you are doing two different things. In the first, you are passing a function to
$.post
. In the second, you are callingcallback
and passing its return value to$.post
(which isundefined
). You'd have to do:$.post( url, params, callback);
.无法回答问题1,也许是服务器应用程序在告诉该消息?
在 issue2 中,这样做(从 $.post 定义中删除“数据”):
Can't give an answer to issue1, maybe is the server application who is telling that message?
In issue2, do it like this (remove "data" from $.post definition):