jQuery$.ajax调用可以在Chrome中使用,但不能在任何其他浏览器中使用

jQuery $.ajax call works in Chrome, but not any other browser

本文关键字:但不能 浏览器 其他 任何 Chrome ajax 调用 jQuery      更新时间:2023-09-26

以下调用在Chrome中运行良好,但在其他所有浏览器中都会失败。

function getInfo(r,c,f){
  return $.parseJSON($.ajax({
      url: baseURL + 'somethingAPI/getInfo',
      data: {
        "data_r": r,
        "data_c": c,
        "data_f": f
      },
      //success: function(data){},
      dataType: "json",
      async: FALSE
    }).response);
}

是的,我使用的是同步ajax调用,我认为这是必要的,因为我不希望任何其他JS在没有执行和返回数据的情况下运行。尽管如此,我不完全确定成功回调是否会发生其他事情。

无论如何,在Chrome中,我可以获得响应对象(JSON),并可以在其中访问数据。

有人知道我做错了什么吗?

关于你不知道如何避免async: false的观点,这是你想要实现的吗?

function getInfo(r, c, f, callback) {
  $.ajax({
    url: baseURL + 'somethingAPI/getInfo',
    data: {
      "data_r": r,
      "data_c": c,
      "data_f": f
    },
    dataType: "json",
    success: callback,
  });
}
getInfo('foo', 'bar', 'baz', function(response) {
  console.log(response);
});

这里是我用来克服这些挑战的语法

    $.ajax({
       url: "pagegoeshere.php",                   
       timeout: 30000,
       type: "POST",
       data: 'data1='+data1+'&data2='+data2,
       dataType: 'json',
       error: function(XMLHttpRequest, textStatus, errorThrown)  {
         alert("An error has occurred making the request: " + errorThrown)
       },
       success: function(returnjson){                                                                                                   
           var returnstuff = returnjson.returnstuff;
           //Do next Javascript step here
       }
});

您可以在成功中运行随后的javascript/jquery,并在Ajax调用成功时将事件"堆叠"在一起。这样,如果它起作用,它就会继续。否则,错误处理可能会以您定义的方式出现在所提供的错误部分中。我通常会在点击处理程序上启动ajax调用,但在您选择的函数中运行它肯定是可行的。请务必检查返回的JSON(例如,可以从处理页面邮寄),以确保它是有效的JSON。Jsonlint是你的朋友!

我已经让chrome有效地解析了糟糕的HTML和JSON,而其他浏览器在好几次都没有。我怀疑正是这些东西特别引起了你的问题。

相关文章: