dpo15099 2012-03-21 20:57
浏览 49
已采纳

如何在ajax中获得多个输出?

I'm using ajax in wordpress to get the output of a function:

jQuery.ajax({
            type: "POST",
            url:"wp-admin/admin-ajax.php",
            data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
            success:function(results){
                jQuery(".semester_selection").empty();
                jQuery(".semester_selection").prop('disabled', false);
                jQuery(".semester_selection").append(results);
            }
        })

And here's the function I use:

function nafham_list_cats_selection() {
    if(isset($_POST['selection_id'])){ 
        nafham_get_listed_cats($_POST['selection_id']);
        die();

    }
}

Using jQuery ajax I'm able to get the output of the function, but what I need to do is to get multiple outputs like if the function echos two variables, I'd like to be able to use the two values separated in the ajax response, is that possible?

  • 写回答

1条回答 默认 最新

  • douwo5710 2012-03-21 21:45
    关注

    Make an array of your output, for example if you have in your php file

    // Some code here and finally you've an array to echo/send to the browser i.e.
    $data=array("id"=>1, "text"=>"This is some content"); // This is your data array/result
    echo json_encode($data); // use json_encode to convert it to json encoded string
    

    Above code will send following json encoded string to the browser

    {"id":1,"text":"This is some content"}
    

    in your ajax success callback function you can convert it to a json object using 'parseJSON'

    jQuery.ajax({
            type: "POST",
            url:"wp-admin/admin-ajax.php",
            data:'action=nafham_list_cats_selection&selection_id=' + $selection_id,
            success:function(results){
                var obj=$.parseJSON(results); // now obj is a json object
                alert(obj.id); // will alert "1"
                alert(obj.text); // will alert "This is some content"
            }
        });
    

    This is only an example and hope it'll help you to understand. for more try this and this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题