javascript 重定向到从 json 响应中获取的 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20089022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:40:11  来源:igfitidea点击:

redirect to url taken from json response

javascriptphpjqueryjsonredirect

提问by Jamol

I am using jquery ajax method to make http request to php webpage, and in response I am taking json like {"status":"success","url":"http url"}

我正在使用 jquery ajax 方法向 php 网页发出 http 请求,作为回应,我正在使用 json,如 {"status":"success","url":"http url"}

on success function I am redirecting to url from json but most of the time it fails. I am using following to redirect:

在成功功能上,我从 json 重定向到 url,但大部分时间它都失败了。我正在使用以下重定向:

window.location.href = url

It works fine when url is clean with no other characters, but fails when I have # or space or some other characters. Please letme know if there is any way to solve my problem.

当 url 干净没有其他字符时它工作正常,但当我有 # 或空格或其他一些字符时失败。请让我知道是否有任何方法可以解决我的问题。

回答by Darren

I personally use

我个人使用

    window.location.replace(url);

Read More- "The replace() method replaces the current document with a new one" window.location.replace()better simulates a http redirect

阅读更多- “ replace() 方法用一个新文档替换当前文档window.location.replace()更好地模拟了 http 重定向

There are other various options like:

还有其他各种选项,例如:

window.location.href = "http://stackoverflow.com";

Which acts as a link click

用作链接点击

回答by masadwin

have u tried window.location = "url"

你试过 window.location = "url"

url should include http://

url 应该包括 http://

and it should be inside quotes

它应该在引号内

回答by Oki Erie Rinaldi

if you use jquery it would be easier. here's an example:

如果你使用jquery,它会更容易。这是一个例子:

function save(){
var item = "value of some input";
 $.ajax({
  url      : "process.php",
  dataType : "json",
  data     : "item ="+item,
  type     : "POST",
  cache    : false,
  success : 
  function (data){
// if the return of your json like {"status":"success","url":"http url"}
// use this
    if (data.status == "success"){
      window.location.href = data.url;
    }
    else{
      alert("error occured");
    }
  }
 });
}