简体   繁体   English

跨域jQuery.Ajax请求-Chrome扩展

[英]Cross-Domain jQuery.Ajax request - Chrome extension

I would like to realize an Google Chrome extension, which would show a notification following the result of an Ajax request. 我想实现一个Google Chrome扩展程序,该扩展程序将在Ajax请求的结果之后显示一条通知。

I coded the function which allows to create a notification, so I just have to do the Ajax request which fetches a .php file on a remote server which belongs to me. 我对允许创建通知的函数进行了编码,因此我只需要执行Ajax请求即可在属于我的远程服务器上获取.php文件。 This request just failed, nothing happened. 该请求只是失败了,什么都没发生。 Nevertheless when I try to realize the request since my server towards my server (without the extension), no problem, I deducted from it that it was a problem of "Cross-Domain"... 但是,当我尝试将请求从服务器移向服务器(不带扩展名)时没问题时,我从中推断出这是“跨域”问题...

Here are the important elements (for the problem) of the manifest.json (I just put all possible permissions^^) : 这是manifest.json的重要元素(用于解决问题)(我只放了所有可能的权限^^):

{
    "background": {
        "scripts": ["myScript.js", "jquery-2.1.4.min.js"]
    },
    "manifest_version": 2,
    "permissions": [ "http://*/", "https://*/" , "http://*/*" , "https://*/*", "tabs", "notifications", "browsingData", "webRequest", "webNavigation" ],
    ...
    ...
}

Here is the AJax request in myScript.js : (The spawnNotification function works perfectly, tested without the request) 这是myScript.js中的AJax请求:(spawnNotification函数可以完美运行,无需请求即可进行测试)

$.ajax({
    url: "http://www.domain.com/test/get.php",
    type: "GET",
    crossDomain : true,
    success: function() {
        spawnNotification("Title", "work", "img/notif.png", "http://www.domain.cor/forum/");
    },
    error: function() {
        spawnNotification("Title", "error", "img/notif.png", "http://www.domain.co/forum/");
    }
});

And finally, the get.php file : 最后是get.php文件:

<?php

header("Content-Type: text/plain");
header("Access-Control-Allow-Origin: *");

$str = 15;
echo $str;

?>

What am I doing wrong here? 我在这里做错了什么? Thanks ! 谢谢 !

( Here are some topics that did not help me... (以下一些主题对我没有帮助...

Chrome extension Cross Domain Request Chrome扩展程序跨域请求

Chrome extension xhr cross domain request gives error:"is not allowed by Access-Control-Allow-Origin." Chrome扩展程序xhr跨域请求给出错误:“ Access-Control-Allow-Origin不允许。” )

You need to provide more response headers than just that one, see the Cross-Origin Resource Sharing specification for details. 您不仅需要提供更多响应头,还请参见跨域资源共享规范以获取详细信息。

Here's pseudo-code (from my other answer here ) of what's required in your server code (sorry, don't write much PHP, hence pseudo-code): 这是服务器代码中所需要的伪代码(从我这里的其他答案)(很抱歉,不要写太多PHP,因此是伪代码):

// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
    // Requests from a `file://` path seem to come through without an
    // origin or with "null" (literally) as the origin.
    // In my case, for testing, I wanted to allow those and so I output
    // "*", but you may want to go another way.
    corsOrigin = "*"
}

// Decide whether to accept that request with those headers
// If so:

// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
    // Done, no body in response to OPTIONS
    stop
}
// Process the GET or POST here; output the body of the response

@TJ Crowder @TJ人群

Thanks Crowder, I tried to write it in PHP and I first tried that for my get.php : 感谢Crowder,我尝试用PHP编写它,而我首先为get.php尝试了它:

<?php
header("Content-Type: text/plain");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

$str = 15;
echo $str;
?>

It doesn't work so I searched a bit with what you said, and found that https://stackoverflow.com/a/9866124/5733765 它不起作用,所以我搜索了一下您所说的内容,发现https://stackoverflow.com/a/9866124/5733765

get.php : get.php:

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

$str = 15;
echo $str;
?>

But still doesn't work 但是还是不行

I found the problem... we have to use xhr 我发现了问题...我们必须使用xhr

myScript.js : myScript.js:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://domain.com/test/get.php", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.send();

Thanks for your help ;) 谢谢你的帮助 ;)

EDIT: the real problem was to define jquery.js after in the myScript.js manifest.json: 编辑:真正的问题是在myScript.js manifest.json之后定义jquery.js:

"background": {
        "scripts": ["jquery-2.1.4.min.js", "notification.js"]
},

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

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