javascript - 如果返回的数据是 javascript,$.ajax 会自动执行脚本吗?

标签 javascript php jquery ajax

我使用单个 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 函数显示文本或从服务器执行脚本。

$.ajaxoutput_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/

相关文章:

javascript - 创建一个滑动图片库

javascript - 删除jquery中的div子元素

javascript - 当我在调试器中看到更改时,为什么我的元素没有显示其属性已更改?

javascript - 如何在 Javascript 中检查一个值是否是整数(特殊情况 1.0 应该是 float )

php - mysql select distinct 同时忽略一列

php - 我是否需要一个框架来在 PHP 中构建 REST API?

javascript - 使用正则表达式仅在 JavaScript 中查找和替换完整单词

javascript - 自动完成 UI 问题

php - 从资源创建流

javascript - 如何使用html2canvas和jspdf以正确和简单的方式导出为pdf