我使用单个 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 代码。我们可以在 the documentation 中看到这一点:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
因此,如果您不指定 dataType
,jQuery 将从响应中找出它。好的,但是它对 "script"
值有什么作用呢?再往下:
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
稍后在讨论中:
If
script
is specified,$.ajax()
will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
所有这些都可以在文档中轻松找到,只需在页面上搜索“JavaScript”一词即可。
关于javascript - 如果返回的数据是 javascript,$.ajax 会自动执行脚本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510516/