【问题标题】:Using $ajax to retrieve content [duplicate]使用 $ajax 检索内容 [重复]
【发布时间】:2013-03-27 05:07:11
【问题描述】:

我正在使用这个fork of Pageguide.js 来提供一些关于使用我的网络应用程序的各个页面的指导。这很好用,但是目前指南的所有内容都是在脚本中静态设置的:

var guide = {
  id: 'jQuery.PageGuide',
  title: 'What can I do here?',
  steps: [
    {
      target: '#user-tools',
      content: 'Some static content here'
    }
  ]
}

$(function() {
  // Load the default guide!
  $.pageguide(guide);
});

我希望使用对服务器的$ajax 调用动态检索内容,因此我将代码更改为以下添加$ajax 调用:

var guide = {
  id: 'jQuery.PageGuide',
  title: 'What can I do here?',
  steps: [
    {
      target: '#user-tools',
      content: function() {
        $.ajax({
          type: 'GET',
          url: 'user-guide',
          data: {elementId: '#user-tools'},
          success: function(html) {
            return html;
          }
        });
      }
    }
  ]
}

虽然$ajax 调用似乎可以正常工作(我使用 Chrome 调试器进行了检查,我可以看到返回了正确的 html,并且日志中没有出现任何错误),但该指南并未使用从服务器返回的 html 进行更新.

我做错了什么?

【问题讨论】:

  • 无法从 Ajax 返回,只需从success 处理程序成功运行一些代码。

标签: javascript jquery


【解决方案1】:

这不行,内容将包含一个XHR 对象。你can't return data from an asynchronous AJAX call。您需要在 AJAX 返回后运行代码:

$.ajax({type: 'GET',url: 'user-guide', data: {elementId: '#user-tools'}}).done(function(html){
  var guide = {
      id: 'jQuery.PageGuide',
      title: 'What can I do here?',
      steps: [{target: '#user-tools',content:html}]
  };
  //rest of your code goes here       
});

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 2017-07-11
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多