我使用一个JS文件将所有数据发布回我的服务器,使用:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
var ct = xhr.getResponseHeader("content-type") || "";
if(ct.indexOf("text/plain") > -1){
alert(response);
console.log('text - response');
}
if(ct.indexOf("text/javascript") > -1){
//eval(response);
console.log('javascript - response');
}
}
});
它在服务器端完成了一系列功能,但最终达到了以下功能:output_javascript("alert('item added');");
function output_javascript($script)
{
header("content-type:text/javascript");
echo $script;
}
这个想法是让$.ajax
函数从服务器显示文本或执行脚本。
当$.ajax
从output_javascript("alert('item added');");
获得响应时,它执行代码两次。当我注释掉要在成功函数中执行的代码时:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
}
});
然后它只执行一次响应。让我相信$.ajax
在返回response
变量中的脚本之前执行代码。
这是真的吗,还是我没有正确理解$.ajax
?如果我误解了$.ajax
的功能,有人能告诉我如何解决这个问题吗?
ajax
将执行返回的JavaScript代码。我们可以在文档中看到这一点:
dataType(默认值:Intelligent Guess(xml、json、script或html))
类型:字符串
您期望从服务器返回的数据类型。如果没有指定,jQuery将尝试根据响应的MIME类型来推断它(XML-MIME类型将产生XML,在1.4中JSON将产生JavaScript对象,在1.4脚本中执行脚本,其他任何内容都将作为字符串返回)。可用的类型(以及作为成功回调的第一个参数传递的结果)是:
因此,如果您不指定dataType
,jQuery将从响应中找出它。好吧,但它对"script"
值有什么作用?再往下看:
"脚本":将响应求值为JavaScript,并以纯文本形式返回。通过附加查询字符串参数"禁用缓存_=[TIMESTAMP]";,到URL,除非缓存选项设置为true。注意:这将把POST转换为远程域请求的GET。
稍后讨论:
如果指定了
script
,$.ajax()
将执行从服务器接收的JavaScript,然后将其作为字符串传递给成功处理程序。
所有这些都可以通过简单地搜索单词"在文档中容易地找到;JavaScript";在页面上。