首页 > 解决方案 > 数据中带有 location.href 的 jquery ajax 帖子不起作用

问题描述

如果使用(或)作为数据,是什么阻止类型POST获得预期结果?location.hrefwindow.location.href

此代码不起作用(它不返回任何内容):

$.ajax({
    type: "POST",
    url: 'page.asp',
    data: {'q': location.href},
    success: function(short_link,status){ 
        console.log('short_link = '+short_link);
        console.log('status = '+status);
    }
});

在此处输入图像描述

我确实看到q值是在浏览器网络信息中发送的,但不知何故,由于302 对象移动状态代码,POST 似乎被重定向到 GET 。就像那里所说的那样:返回重定向作为对 XHR 请求的响应

在此处输入图像描述

但是,如果我将其更改为data: {'q': 'to some string'}它可以工作。

此外,如果我更改要使用的代码GET(以及相应的代码'page.asp'),它也可以工作:

$.ajax({
    type: "GET",
    url: 'page.asp?q='+location.href,
    success: function(short_link,status){ 
        console.log('short_link = '+short_link);
        console.log('status = '+status);
    }
});

标签: jqueryajaxpostlocationhttp-status-code-302

解决方案


我认为您必须对 url 进行编码,以替换特殊字符。


推荐阅读