开发者

"Access is denied." error on IE8 using JQuery .ajaxForm()

Greetings all,

I'm an AJAX newbie, and I'm having a problem with same origin policy protection using JQuery 1.4.4 and the jquery.form.js AJAX plug-in.

I have an AJAX contact form which works fine so long as visitors preface URL's they type in with "www". But if they navigate to my site (not using www), the URL still resolves OK but the URL doesn't match what I use in my AJAX form. In Chrome, this results in a console error:

"XMLHttpRequest cannot load http://www.example.com/. Origin http://example.com is not allowed by Access-Control-Allow-Origin."

And on IE8 I get "Access is denied". So even though the URL's resolve OK with or without "www", my AJAX form won't work if the visitor doesn't preface with "www". If I change my AJAX form code to post to http://example.com (without "www") then it won't work if visitors navigate to www.example.com. I can't think of how to make my code handle either condition. This has got to be an issue that nearly everyone would run into who is using AJAX, regardless of using JQuery. So I must be missing something obvious. Can someone please educate me on t开发者_开发问答his? My test code is below.

Thanks,

Northk

<!DOCTYPE html> 
<html>
<head> 
<meta charset="utf-8"> 
<title>ajaxForm Error Test</title> 
<script src="http://www.example.com/js/jquery-1.4.4.min.js"></script> 
<script src="http://www.example.com/js/jquery.form.js"></script>    
</head> 
<body>
<form id="contact-form" method="post" action="http://this-url-wont-be-used.com/">
<a href="#" id="contact-button">SEND</a>
</form>
<script>
//
// hook up the form to ajax
//
$('#contact-form').ajaxForm({
    url: 'http://www.example.com/', // forcing the URL doesn't seem to help!
    success: function(data) {
        alert(data);
    },
    dataType: 'html'
});
//
// make the SEND link behave as if it's a submit button
//
$('#contact-button').click(function(e) {
  $('#contact-form').submit();
});
</script>
</body>
</html>


The domain www.xyz.com and the domain xyz.com are not the same so you'll get this error if you've hardcoded urls in your Javascript files.

The short answer is ot use relative urls rather than full urls. You don't show actual urls so I can't give you an exmaple in your case but lets say the the domain was http://www.xyz.com and you need to post the form to the url http://www.xyz.com/admin/form/

In your javaScript the url you'd use is /admin/form

That way no matter what url your visitor uses to get to your site it will work and it won't result in a cross domain scripting error.

Of course if your site is public you should probably (permanently) redirect your xyz.com site to the www.xyz.com site. Because Google and other search engines consider these two to be different domains and your page ranks will be divided across the two domains.


try using relative path for url url: '/',

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜