简体   繁体   English

带有CI的Chrome扩展程序中的XHR

[英]XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. 我正在从chrome扩展内容脚本向我控制的服务器发送POST I setup the permissions in the manifest ok. 我在清单中确定权限。 Here is my XHR code. 这是我的XHR代码。 (I want to avoid jQuery for this). (我想避免使用jQuery)。 Its sending an empty responseText 它发送一个空的responseText

var xhr = new XMLHttpRequest();
    xhr.open("POST",'http://mysite.com/make',true);
        xhr.onreadystatechange=function() {
            if (xhr.readyState == 4) {
                var res = JSON.parse(xhr.responseText);
                console.log(res);
            }
    }

    xhr.send({'textbox':data[0].user,'from':'extension'});

data[0].user is an object I got directly from the Twitter API data[0].user是我直接从Twitter API获得的对象

in my CI controller I have 在我的CI控制器中

$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);

$fullURL = 'http://www.google.com'; //example of a URL from code.

$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));

The response text is empty 响应文本为空

a jquery call on the other hand works fine 另一方面,一个jQuery调用工作正常

$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
  function(data) {
    console.log(data);
});

Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server. 原因很简单,JQuery post方法可以接受JSON,然后将其转换为字符串并发送到服务器。

What you are trying to do is to directly send JSON here : 您尝试做的是在此处直接发送JSON:

xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way

send method should either accept NULL or a string which is generally made up of QueryString Parameters like . send方法应接受NULL通常由QueryString参数(如)组成的字符串

xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way

This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters. 这将确保您的数据去与文本相应的URL,并作为POST请求的参数。 and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL. 和queryString会像在数据包正文中的textbox = username1234&from = extension那样生成,这与在Get中带有URL旁边的标头不同。

jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters. jQuery的post方法使您更轻松地格式化使用JSON发送的数据,然后在内部将其转换为queryString以发送参数。 You can't directly send Javascript object like that with an XHR object! 您不能像XHR对象那样直接发送Javascript对象!

Also checkout this example: 还要检查这个例子:

http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/ http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM