【问题标题】:Enabling cross origin request启用跨源请求
【发布时间】:2015-07-05 06:47:16
【问题描述】:

这是我的代码。我正在从本地主机连接到本地主机 8080 上的服务器,我收到错误,因为它的来源不同。我查看了很多有用的链接,但我不知道如何将它们与这段代码结合起来。以下是我提到的一些链接。

CORS - Cross-Domain AJAX Without JSONP By Allowing Origin On Server

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

   <!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 

<form action="http://localhost:8080/newjersey/rest/hello" name="ajaxform" id="ajaxform" method="GET">
ID:<br>
<input type="text" name="ID">
<br>
Notes:<br>
<input type="text" name="notes">
<br><br>
Ignore:<br>
<input type="checkbox" name="ignore[]" value="1">Avg
<input type="checkbox" name="ignore[]" value="2">Time

<input type="submit" value="Submit">
</form> 

<script>
//callback handler for form submit

$("#ajaxform").submit(function(e)
{
    //$(this).addHeader("Access-Control-Allow-Origin", "*");
    //alert("Its here");
    var postData = $(this).serializeArray();
    var formURL = $(this).attr("action");
    //var formURL = "http://localhost:8080/newjersey/rest/hello/";
    //alert(formURL);
    $.ajax(
    {
        url : formURL,
        type: "GET",
        data : postData,
        success:function(data, textStatus, jqXHR) 
        {
            //data: return data from server
            //alert("Success " + textStatus);
        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            //if fails      
        }
    });
    e.preventDefault(); //STOP default action
    $(this).unbind(e); //unbind. to stop multiple form submit.
});

$("#ajaxform").submit(); //Submit  the FORM
</script>

</body>
</html>

【问题讨论】:

    标签: html ajax cors


    【解决方案1】:

    您是否尝试过在 SERVER 上允许外国来源?

    在服务器端添加这个! (运行 apache/nginx 的地方)

    Access-Control-Allow-Origin: *
    

    apache2 或 htaccess 中的示例:

    <FilesMatch "\.(js)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
    </FilesMatch>
    

    【讨论】:

    猜你喜欢
    • 2016-11-23
    • 2017-07-27
    • 2017-02-26
    • 2020-05-02
    • 2018-10-20
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多