简体   繁体   English

PHP和jQuery中的Ajax调用

[英]Ajax Call in PHP and jQuery

This is my functions.php script containing the following code. 这是我的functions.php脚本,其中包含以下代码。 The array is encoded into JSON. 该数组被编码为JSON。

functions.php functions.php

 $final['custom']['main'] = queryCustom($conn, $id);
 echo json_encode($final);

My global.js has the following code which makes an AJAX request in jQuery: 我的global.js具有以下代码,可在jQuery中发出AJAX请求:

$.ajax({
            type: "POST",
            url: "functions.php", // file to reach Ajax call
            dataType: "json", 
            data: { 
                action: 'custom',
                id: id,
                  },
                success:
                function(data) {

                setCustom(data.custom);

I want to know what the data contains in function(data) ? 我想知道function(data)包含的data是什么? The setCustom(data.custom) , what does this mean here? setCustom(data.custom) ,这是什么意思? Can someone provide me an explanation of this please? 有人可以给我一个解释吗?

data contains an object literal provided by the server side json_encode(). 数据包含服务器端json_encode()提供的对象文字。 It's been automatically parsed because the data type is set to json. 由于数据类型设置为json,因此已自动进行了解析。

example: 例:

PHP: PHP:

$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);

Will give the following json string (formatted for better understanding): 将给出以下json字符串(格式化以更好地理解):

{
    "custom": {
        "main":[
            {
                "symbol":"MAP4",
                "official_ID":"112315"
            }
        ]
    }
}

The ajax call above is set to datatype json. 上面的ajax调用设置为数据类型json。 jQuery knows if this datatype is set, it will automatically parse the string to an object literal. jQuery知道是否设置了此数据类型,它将自动将字符串解析为对象文字。

Javascript: Javascript:

$.ajax({
    type: "POST",
    url: "url.php", // file to reach Ajax call
    dataType: "json", 
    success: function(data) {
        var main = data.custom;
        console.log(main); // returns the child object with "main"
    }
});

data contains the initial object, custom is a child object of data and main is a child object of custom. data包含初始对象,custom是data的子对象,而main是custom的子对象。

Success: A function to be called if the request succeeds. 成功:如果请求成功,将调用的函数。 The function gets passed three arguments: 该函数传递了三个参数:

  • Data Returned From The Server 服务器返回的数据
  • Status 状态
  • jqXHR (XMLHttpRequest Object) jqXHR (XMLHttpRequest对象)

In your PHP code you've added echo json_encode($final); 在您的PHP代码中,您已经添加了echo json_encode($final); which will be returned if the request is completed successfully. 如果请求成功完成,将返回该值。 The response will be passed to data which you can later use in your front-end code. 响应将传递给您以后可在前端代码中使用的data

You can read more about $.ajax() at http://api.jquery.com/jQuery.ajax/ 您可以在http://api.jquery.com/jQuery.ajax/上了解有关$.ajax()更多信息。

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

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