javascript - Ajax 请求成功但结果为空

标签 javascript jquery html ajax google-chrome-extension

我正在构建一个 Google Chrome 浏览器扩展,它使用 $.ajax 请求将数据从网页发送到我的服务器(目前使用 localhost 托管)。在扩展有权访问的网页 ( more on content scripts) 上下文中执行的 content_script.js 文件运行此代码:

//note: encode64String is assigned earlier in the script...

$.ajax({
type: "POST",
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp",
data: {img: encode64String},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
    console.log("The ajax request succeeded!");
    console.log("The result is: ");
    console.log(data);
},
error: function(){
    console.log("The request failed");
}
});

问题是 Ajax 请求成功了,但是它返回的 data 参数是空的...

代码运行后控制台如下所示:enter image description here

目前uploadedendpoint.php文件的内容是:

<?php
  header("Access-Control-Allow-Origin: *");
  echo 'This comes from php file'; die();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>

这意味着至少应该在 data 变量中返回一些东西。

我已进一步确认请求成功,因为当我将请求发送到损坏的 url(即 uploadddddendpoint.php)时,$.ajaxerror参数被执行。

我读过类似的问题,例如 jQuery $.ajax response empty, but only in Chrome但无济于事...

更新:

我完全删除了无效的第二个 type: "jsonp" 参数并添加了 dataType: "text/html"。每次运行代码时,我现在都会收到失败的 ajax 请求。

更新:奇怪地将 dataType : "text/html" 更改为 dataType : "html" 会导致 ajax 请求成功,但再次使用空白 data 变量。 更新:当使用开发工具包监控网络 XHR 时,这些是已发送/响应的消息:

enter image description here enter image description here

关于可能重复的标志 Impossible to cross site ajax api calls in a chrome extension?我建议否则!我已经调查了那个问题,但问题似乎并不相同。

最佳答案

为什么您的 AJAX 请求中有两个 type 字段? jsonpPOST

$.ajax({
    type: "POST",  // OK
    url: "http://localhost:8888/quartzsite/uploadendpoint.php",
    type: "jsonp", // ???
    // ...
});

更新:

我认为您应该使用 URL 的相对路径。尝试将您的请求更改为以下内容:

$.ajax({
    type: "POST",
    url: "/quartzsite/uploadendpoint.php",
    dataType: "text/html",
    data: {img: encode64String},
    success: function(data){
        console.log("The ajax request succeeded!");
        console.log("The result is: ");
        console.dir(data);
    },
    error: function(){
        console.log("The request failed");
    }
});

您可以看到我将 URL 替换为 /quartzsite/uploadendpoint.php。这可能会解决问题...绝对 URL 可能表示跨域请求,这不是您想要的。

此外,作为旁注,没有必要设置 contentType,因为您设置的内容已经是默认值。如果您要发送 JSON 或 XML,那么您需要设置 contentType。

关于javascript - Ajax 请求成功但结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243319/

相关文章:

javascript - Ajax jquery post 发布时没有变量名

jquery - 单击时更改工具提示文本(切换)

jquery - HTML 元素的反转顺序

html - Bootstrap 嵌套下拉列表

javascript - 基本 Angular 形式验证不起作用

javascript - 如何为函数值创建 React Context 而无需一直重新渲染

javascript - 将我网站中的所有链接更改为 https

javascript - 如何在服务器端通过 DDP 连接订阅到其他 Meteor 服务器?

html - 什么不会图像进入div?

html - 我无法在不破坏我的网站的情况下调整图像大小