javascript - jQuery/Ajax 成功方法实现

标签 javascript jquery ajax

我在 DOM 上准备好了以下 jQuery 函数:

$.ajax({
  url : '/weather/',
  type: 'GET',
  //dataType : "json",
  success : function(data) {
    alert("success");
    var jsondata = Object.keys(data);
    alert(jsondata);
    location = "testing";

    alert(data.weather);
    weather = data.weather;
    $("location").text(location);
  }
  }).setTimeout(executeQuery, 500);

ajax 调用返回一个正确的 json,我用它来更改 html 的值。然而,当这一行执行时,

$("location").text(location);

页面被重定向到一个 URL,该 URL 附加了上面一行中的“location”值。我在其他地方使用了这些行,但没有使用成功函数调用。

有人可以帮我做什么来防止发生这种重定向吗?

最佳答案

其一,您的类别或 ID 选择器无效。应该是:

$(".location").text(location);

$("#location").text(location);

取决于您的 html 标记是否分别使用“location”的类或 id。

此外,在这种特殊情况下,您缺少 var 这个词:

var location = "testing";

导致浏览器假定顶级窗口范围。 window.location 是在您设置其值时重定向的属性。

关于javascript - jQuery/Ajax 成功方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22615284/

相关文章:

javascript - 从我的自定义点击处理程序调用默认事件处理程序?

javascript - 我的变量不能保存 "document.querySelector(".content") ",它返回 null

javascript - 获取child的child的子节点值

javascript - 操作对象数组时 For 循环未按预期工作

javascript - 使用链接样式附加 DIV

jquery - Joomla Jquery 无法工作,这是为什么?

javascript - 在ajax中发送json

php - Jquery Ajax 将 tinyMCE html 发送到 php 页面

javascript - 使用按钮调用 HTML 中的 javascript 文件

javascript - 以编程方式更改按钮颜色