Jac*_*oer 3 javascript php ajax jquery
我使用一个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');
}
}
});
Run Code Online (Sandbox Code Playgroud)
它经历了服务器端的一整套功能,但最终得到了这个: output_javascript("alert('item added');");
function output_javascript($script)
{
header("content-type:text/javascript");
echo $script;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是让$.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
{
}
});
Run Code Online (Sandbox Code Playgroud)
然后它只执行一次响应.让我相信$.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"价值有什么关系?再向下:
"script":将响应评估为JavaScript并将其作为纯文本返回.通过将查询字符串参数"_ = [TIMESTAMP]"附加到URL来禁用缓存,除非缓存选项设置为true.注意:这会将POST转换为GET以获取远程域请求.
后来在讨论中:
如果
script指定,$.ajax()则在将其作为字符串传递给成功处理程序之前执行从服务器接收的JavaScript.
只需在页面上搜索单词"JavaScript",就可以在文档中轻松找到所有这些内容.
| 归档时间: |
|
| 查看次数: |
1078 次 |
| 最近记录: |