【问题标题】:Breaking up AJAX return [duplicate]分解AJAX返回[重复]
【发布时间】:2012-09-06 20:57:58
【问题描述】:

可能重复:
How to use split?

我正在尝试基于插件创建动态内容 div。默认情况下,插件采用 slides 对象并将其以逗号分隔。每个逗号后面的每个字符串都是分隔的。但是,当通过 AJAX 返回一个值时,它被解释为一个长字符串,而不是被分解。如何让 jQuery 将其拆分为多个字符串?

阿贾克斯:

$.ajax({
url: 'backend/index.php',
data: {'check':'true'},
type: 'POST',
async: false,
success: function(data) {
    var carousel,
    el,
    i,
    page,
    slides = [ data ];
}
};

当前正在返回的数据:

echo "
    '<strong>Swipe</strong> to know more &gt;&gt;&gt;<br>Or scroll down for <em>Lorem Ipsum</em>',
    '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.',
    '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.',
    '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.'
";
exit();

幻灯片的默认示例:

slides = [
    '<strong>Swipe</strong> to know more &gt;&gt;&gt;<br>Or scroll down for <em>Lorem Ipsum</em>',
    '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.',
    '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.',
    '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.'
];

作为参考,这里使用的是 SwipeView 插件:http://cubiq.org/swipeview

【问题讨论】:

  • 要么为您的字符串添加一个分隔符并在分隔符上拆分它(例如 | 和 data.split("|")),或者,将您的数据作为有效 JSON 返回并将数据类型更改为 JSON
  • 你不返回 JSON 对象的原因是?
  • async: false - 为什么,哦,为什么??? :)

标签: javascript string split


【解决方案1】:

哦,伙计,这是一个糟糕的问题。提交后几分钟,我意识到它是多么容易。

编辑后端 PHP 以返回:

$result = array('<strong>Swipe</strong> to know more &gt;&gt;&gt;<br>Or scroll down for <em>Lorem Ipsum</em>','1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.','2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.','3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.');

echo json_encode($result);

然后简单的添加到ajax中:

dataType: "json",

感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多