繁体   English   中英

传递回调参数 ajax post

[英]passing callback parameters ajax post

我需要一些有关 ajax 回调的帮助。 在调用 ajax 之后,我试图传递某些参数

        var dataString = 'string=' + string;
        $.ajax({
            type: "POST",
            url: "file.php",
            data: dataString,
            success: function(data){

                $(".selector").html(data)

        }
        });

好的,如果我的 file.php 有一些 mysql 查询,我正在尝试回显值

echo $picture;
echo $title;
echo $additional_values;

如何回显某些值并将其传递给 ajax

So if I echo those out in my php file, and output it through my ajax function(data), it will output everything into $(".selector").html(data) ( <div class="selector"></div> ),但是,我正在尝试 output 一次做一件事

success: function(data){
  $(".picture").html(data); // echo's out picture in my picture div class
  $(".title").html(data); // echo's out title in my title div class
  $(".additional_values").html(data); // echo's out to the div class...
}

如果有人可以向我照射一些光,那就太好了!

谢谢!

PHP

$data = array('picture'=>$picture,
              'title'=>$title,
              'values'=>$additional_values,
             );

print json_encode($data);

JavaScript

    var dataString = 'string=' + string;
    $.ajax({
        type: "POST",
        url: "file.php",
        data: dataString,
        datatype: 'json',
        success: function(data){
            $(".picture").html(data.picture);
            $(".title").html(data.title);
            $(".additional_values").html(data.values);

        }
    });

您可以使用 JSON。 JSON 是一种序列化格式,允许您“转换” object 以将字符串转换回 object。 PHP 有一个内置的 function 编码为 JSON 字符串,称为json_encode

PHP代码

file.php
<?php
//... Your logic here
header("Content-type: application/json"); //'Tell' the browser that it's a JSON response
$returnData = array('picture'=>$picture, 'title'=>$title, 'values'=>$additional_values);
echo json_encode($returnData); //Encode $returnData to JSON string
?>

现在,jQuery 可以接收此字符串并将其自动转换为 javascript object。 我们在data参数中有一个 object

JavaScript

var dataString = 'string=' + string;
$.ajax({
    type: "POST",
    url: "file.php",
    data: dataString,
    success: function(data){
       //At this point, data is just as php's $returnData, so it has 3 properties
       //picture, title and values.
       $(".picture").html(data.picture);
       $(".title").html(data.title);
       $(".additional_values").html(data.values);
    }
});

JSON 有多种语言版本,是 AJAX 中事实上的交换格式。 有关http://json.org的更多信息。

希望这可以帮助。 干杯

暂无
暂无

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

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