无法弄清楚为什么不发送AJAX请求

时间:2012-10-03 18:02:25

标签: google-chrome-extension

我即将创建我的第一个Chrome扩展程序(它是一个弹出窗口),它会将数据发送到服务器。 以为这很容易,但我卡住了。

manifest.json中的

我为“http:// mypage [dot] com /”以及“http:// mypage [dot] com / *”设置权限,以便我可以访问“mypage [dot] com / api“必须将数据发送到的地方。 所以我的popup.html看起来像:

     <!doctype html>
     <html lang="en">
       <meta charset="UTF-8">
       <title>myExtension</title>
     </head>
     <body>
       <form name="myform">
         <input type="text" name="myText" id="myText"/>
         <input type="submit" name="senden"/>
       </form>
     </body>
       <script src="jquery-1.8.2.min.js"></script>
       <script src="popup.js"></script>
     </html>

所以我的popup.js看起来像:

      document.forms["myForm"].addEventListener("submit", sendRequest)
      function sendRequest() {
        var myVar= $('#mytext').val();
        var myrequest= $.ajax({
            type: 'POST',
            url: 'http://mypage.com/api/',
            data: {screen_name: 'myname', api_key: 'myKey', var1: myVar},
            success: function(data, textStatus){
                           alert('request successful');
                     },
            error: function(xhr, textStatus, errorThrown){
                        alert(xhr); alert(textstatus); alert(errorThrown);
                     }
            });
       }

现在,当我按下提交按钮时,它只会给我这三个警报,第一个警告:[object Object],第二个:错误,第三个只是空。

我试图解决这个问题,但我不知道错误在哪里。我还读到了一些background.html和content_script.js,但我不知道我有什么用它们和我在互联网上发现的一些扩展,只包含popup.html和popup.js,它们工作得很好应该做的(例如domai.nr-extension)。

所以我对我必须使用的一些解释以及在弹出扩展中正确发布数据的做法感到非常高兴。

3 个答案:

答案 0 :(得分:0)

首先,你关闭头部标签,但不要打开它

尝试为您的表单添加ID

<form id="myform">

然后我会像这样简化js代码

$('#myform').submit(function(){

    var myVar= $('#mytext').val();

    $.ajax({
        url: "http://mypage.com/api/", 
        type: "POST",        
        data: {screen_name: 'myname', api_key: 'myKey', var1: myVar},   
        success: function(data, textStatus){
            alert('request successful');
        },
        error: function(xhr, textStatus, errorThrown){
            alert(xhr); alert(textstatus); alert(errorThrown);
        }
    });

});

答案 1 :(得分:0)

<强>问题

如果你想进行Cross-Origin ajax调用,你需要request appropriate permissions

<强>调试

调试变量的方法比alert()更好console.log()。要查看此方法的输出,您需要打开一个控制台。要打开弹出窗口的控制台:打开弹出窗口,右键单击它并选择“检查元素”。当开发者工具打开时,导航到“控制台”选项卡。您将从console.log(xhr)获得比从alert(xhr)获得的更多信息。此外,在控制台上打印出所有权限警告,无效语法警告等,以便于查找错误。

弹出式广告中的AJAX

从弹出窗口发送POST请求有一周的时间点:当弹出窗口关闭时(它很容易关闭 - 当用户点击弹出窗口外的内容时),请求被取消。你提到的是background page。背景页面工作在(惊喜,惊喜)背景中,不能轻易关闭。你的弹出窗口应该communicate和背景页面,并要求它进行ajax调用。如果这样做,后台页面将执行AJAX调用,即使弹出窗口可能已经关闭。

答案 2 :(得分:0)

http://mypage.com/api/中查看您的功能。 通过编写简单的响应来测试它:

function nameOfFunciton(){
    echo "test";
}

如果您看到“请求成功”提醒,则代码中存在问题。

相关问题