如何在弹出窗口中使用XHR

时间:2013-12-03 11:15:59

标签: javascript google-chrome-extension popupwindow

您好我需要知道如何从弹出窗口中读取API。 这是我的弹出窗口

<!DOCTYPE html>
 <html>
<head>
    <script type="text/javascript" src="test.js"></script>       
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
    <form id="userinfo">
        <label for="user">&nbsp;Email&nbsp;&nbsp;&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
        <input type="text" id="user" /><span id="semail"></span>
        <br><br>
       <label for="pass">Password&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;</label>
       <input type="password" id="pass" />
        <br>
        <br>
        <input type="button" id="login" value="Log In"/>
    </form>
   </body>
</html>

这是我的test.js

window.addEventListener('DOMContentLoaded', function() {
var user  = document.querySelector('input#user');
 var pwd  = document.querySelector('input#pass');
var login = document.querySelector('input#login');

 login.addEventListener('click', function() {     

    var userStr = user.value; 
    var pwdStr = pwd.value;

    var req = getHTTPObject();;
    var url="http://blog.calpinetech.com/test/index.php";
    req.open("GET", url);
    req.send(null);
    if (req.status == 200) {        
       var item=req.responseText;
       alert(item);
    }
    window.close();

     chrome.runtime.getBackgroundPage(function(bgPage) {
            bgPage.updateIcon();
        });

      }); 

   });

在这里,当我点击登录按钮时,它必须读取API(名为“http://blog.calpinetech.com/test/index.php”的服务器文件)。我该怎么办?请帮帮我

1 个答案:

答案 0 :(得分:0)

顺便说一下,没有使用XMLHttpRequest进行AJAX调用的原因是什么?

您的事件监听器中的示例可能会有所帮助:

var userStr = user.value, 
    pwdStr = pwd.value,
    url="http://blog.calpinetech.com/test/index.php";
if (window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.send("username="+userStr+"&passwd="+pwdStr);

/** Handle your response here */