首页 > 解决方案 > 如何修改 ajax 函数的响应 url?

问题描述

我有一个 ajax 函数,它在成功时重定向到从 url 返回的响应:

document.getElementById("button1").addEventListener("click", function (e) {
    e.preventDefault();
    $.ajax({
        url: 'http://localhost:8080/someLoginUrl',
        method: 'GET',
        crossDomain : true,
        xhrFields: {
            withCredentials: false
        },
        success: function(response){
            window.location.href = response;
        }
    });
});

返回的响应http://localhost:8080/someLoginUrl只是一个网页,其中包含一个 url:

这是响应页面的html:

<html><head></head><body>https://localhost:8080/anotherLogin</body></html>

所以,一旦我点击我的按钮button1,而不是重定向到http://localhost:8080/someLoginUrl,它重定向到https://localhost:8080/anotherLogin,这是我想要的行为。但是,我想对函数response内部进行一些小操作success- 我想将协议从 更改httpshttp. 我怎么做?

我试过response = response.replace('https', 'http');了,但这并没有改变任何东西。

标签: javascriptjqueryajax

解决方案


可能是我理解你的问题!您希望将成功响应数据发送到发生此操作的同一页面

首先,您必须创建一个带有 id 的潜水<div id=res_data> </div>并将此 div 放置在您要显示响应数据的位置。

然后你的最终代码是

document.getElementById("button1").addEventListener("click", function (e) {
  e.preventDefault();
  $.ajax({
  url: 'http://localhost:8080/someLoginUrl',
  method: 'GET',
  crossDomain : true,
  xhrFields: {
  withCredentials: false
  },
 success: function(response){
    $('#res_data').val(response);
 }
 });
});

如果您觉得这没有帮助,请调整我。


推荐阅读