使用jquery更改文本并获取请求

Change text with jquery and get request

本文关键字:获取 请求 文本 jquery 使用      更新时间:2023-09-26

我的javascript/jquery代码出了什么问题?

<%= link_to 'Click', '#', id: 'link' %><span id="new-data"></span>

<script type="text/javascript" charset="utf-8">
  $("#link").click(function(){
    $.get('http://httpbin.org/get', { name: "John", time: "2pm" }).done(function(data) {
            $("#new-data").text(data);
});
});
</script>

问题可能是您使用的是绝对URL。有些浏览器将绝对URL视为跨域请求,即使不是。请尝试使用相对URL。

$("#link").click(function(){
    $.get('/get', { name: "John", time: "2pm" }).done(function(data) {
            $("#new-data").text(data);
    });
});
  $(document).on("click","#link",function(){
    $.get('http://httpbin.org/get', { name: "John", time: "2pm" }, function(data) {
            $("#new-data").html(data);
    });
});

data中的响应必须在立即回调中,而不是在.done()回调中,后者只在成功时执行,根本不包含响应。

这个代码应该可以工作:来自jquery文档的引用,请在这里找到

<script>
$("#link").click(function() {
 $.get("http://httpbin.org/get", { name: "John", time: "2pm" }, function  (data) {
    $("#new-data").text(data);
  });
}
</script>