启用跨源请求

时间:2015-04-27 00:08:32

标签: html ajax cors

这是我的代码。我从localhost连接到localhost 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>

1 个答案:

答案 0 :(得分:0)

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

在服务器端添加此功能! (apache / nginx运行的地方)

Access-Control-Allow-Origin: *

apache2或htaccess中的示例:

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