jQuery ajax doesn't work on url without www

2019-04-15 20:01发布

The jQuery ajax script below doesn't work on my site if url is without www. I checked Firebug and it doesn't send the ajax call.

$.ajax(
    {
        type: "POST",
        url: "http://www.mysite.com/beta/products.php",
        data: "page_type=index&sort=relevancerank&CartId=<?php echo $CartId;?>&HMAC=<?php echo $HMAC;?>",
        success: function(msg)
        {
            $('#content-holder').html(msg);

        },
        error: function()
        {
            alert("An error occurred while updating. Try again in a while");
        }
    });

4条回答
霸刀☆藐视天下
2楼-- · 2019-04-15 20:34

Is your server redirecting to the "www" domain possibly? This is probably just the same-origin policy preventing your outer page from accessing a different domain.

查看更多
小情绪 Triste *
3楼-- · 2019-04-15 20:41

I'm assuming the calling document URL is referenced as "mysite.com", or "subdomain.mysite.com"? The XMLHttpRequest object (the engine that powers jQuery Ajax calls) can not perform "cross-domain" requests. A subdomain (e.g. 'www') qualifies. Make sure your requests are to the same subdomain.

查看更多
来,给爷笑一个
4楼-- · 2019-04-15 20:43

You don't need to provide an absolute URL, you can simply provide a relative one, and it will work regardless if the your page is loaded with the www. subdomain or not:

//...
    type: "POST",
    url: "/beta/products.php",
//...
查看更多
做个烂人
5楼-- · 2019-04-15 20:48

www. is just a naming convention - ajax will load on any address that can be looked up via dns, or it will work on an ip address as long as there is a server to respond to the request.

BUT - your page location and the ajax request need to be in the same domain for security reasons. To get round this restriction, you need to use something called JSONP

查看更多
登录 后发表回答