从JSON响应中获取URL并重定向

3
我正在使用jquery ajax方法向php网页发出http请求,在响应中,我获取了类似{"status":"success","url":"http url"}的json。
在成功的函数中,我尝试从json中重定向到url,但大多数情��下会失败。我正在使用以下方式进行重定向:
window.location.href = url

当网址干净无其他字符时,它正常运行,但是当我有#、空格或其他一些字符时就失败了。请告诉我是否有解决这个问题的方法。


2
提供一个失败的示例URL... - Hanlet Escaño
我在服务器端使用json_encode函数,因此我认为它会对特殊字符进行编码,并为某些字符创建类似于&abc;的内容 [链接](http://example.com/post.php?s=Subject&p=1&t=Some_text_with_space and_quotation_and_hash)。 - Jamol
3个回答

6
我个人使用的是:
    window.location.replace(url);

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

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

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

这是一个链接点击事件


window.location.replace(url); 没有起作用。我在服务器端使用 json_encode 函数,因此我认为它正在编码特殊字符,但我不知道为什么 window.location.replace(url) 不起作用,它至少应该尝试打开那个 URL,但它什么也不做。 - Jamol
抱歉,我以为我复制粘贴的内容足够了。但是我现在没有我的代码。今晚我会发布一个新帖子,附上我的源代码和一些失败的测试用例。 - Jamol
@jCloud 当你有时间的时候,你可以将代码添加到这篇帖子中。 - Darren

2
如果您使用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");
    }
  }
 });
}

2

你尝试过window.location = "url"吗?

url应该包含http://。

并且应该放在引号内。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接