简体   繁体   English

嵌套在.get请求中的jQuery无法执行

[英]jQuery nested within .get request won't execute

I have the following jQuery get request, which returns html text under the key name "data": 我有以下jQuery get请求,该请求以键名“ data”返回html文本:

$(".article").click(function() {
  $.get("<%= click_path %>", function(data) {
    $(".article").html(data);
  });
});

All the code executes except the line $(".article").html(data); 除了行$(".article").html(data);以外的所有代码都将执行$(".article").html(data); . In fact, any jquery code I put inside the get request fails to execute, even though it all works fine if I move it outside the get request. 实际上,即使我将它移到get请求之外,即使放在我的get请求中的所有jquery代码都无法正常运行,它也无法执行。 Does anyone see anything wrong with my syntax? 有人看到我的语法有问题吗?

jQuery's $.get method is an alias to $.ajax with an assumed HTTP request method of GET and without the ability to specify many options. jQuery的$.get方法是$.ajax的别名,具有假定的HTTP请求方法GET并且无法指定许多选项。 You give it a URL and a function to run on successfully retrieving that URL. 您给它提供一个URL,并提供一个可以成功检索该URL的函数。 It tries to GET that URL and, if it can, the success function will run. 它尝试GET该URL,并且如果可以,则将运行成功函数。 If it can't, or if something is wrong with the response data, it fails silently and will not run the given function. 如果不能,或者响应数据出了点问题,它会静默失败,并且不会运行给定的功能。

That being the case, I would assume your request is failing somewhere. 既然如此,我认为您的请求在某处失败。

You need to look in the developer's console for errors and to inspect the request. 您需要在开发者控制台中查找错误并检查请求。

You can also change your code to use $.ajax and pass in the options, along with your current params, an error method. 您还可以更改代码以使用$.ajax并传递选项以及当前的参数(一种error方法)。 If the error method is called, you'll receive as params the jqXHR instance, a string textStatus , and a string errorThrown . 如果调用error方法,您将收到jqXHR实例,字符串textStatus和字符串errorThrown作为参数。 Pass these into console.log and look at them for clues as to what is wrong as well. 将它们传递到console.log并查看它们以获取有关错误之处的线索。

$(".article").click(function() {
    $.ajax({
        url: "<%= click_path %>",
        success: function(data) {
            $(".article").html(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
});

Chances are, your ajax request fails to execute and as result, your jQuery code inside the callback never runs. 可能是,您的ajax请求无法执行,结果,回调中的jQuery代码将永远无法运行。

Run the following instead and see if an error is alerted: 而是运行以下命令,看看是否警告了错误:

var jqxhr = $.get( "<%= click_path %>", function() {
  alert( "success" );
}
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM