如何从AJAX中的数组php接收json

时间:2018-04-09 19:38:45

标签: javascript php jquery json ajax

我正在进行AJAX调用,并且我尝试从数组json_encode()接收json,但似乎无法正常工作。谢谢你的帮助。

我没有收到任何错误,并且我已经检查了其他一些stackoverflow问题,但无法找到完整的示例。

问题是当调用ajax并从results

返回所有内容时,我没有进入div(#form_response)的任何内容

我使用以下代码获得的回复是:

{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}

HTML&amp; AJAX:

<script type="text/javascript" src="js/jquery.js"></script>

<div class="" id="form_response"></div>

<form id="add_property_form" action="" method="POST">
  <input type="text" name="input">
  <button type="submit">Send</button>
</form>

<script type="text/javascript">
$("#add_property_form").submit(function(evt){  

      evt.preventDefault();
      var formData = new FormData($(this)[0]);
   $.ajax({
       url: 'thescript.php',
       type: 'POST',
       data: formData,
       async: false,
       cache:false,
       contentType: false,
       processData: false,
       dataType: "json",

    success: function (data) {
    $('#form_response').html(data);
    }

  });
return false;
});

</script>

thescript.php

header('Content-Type: application/json');
$success = true;
$false = false;



$results = array(
   'success' => $success,
   'complete' => '<div class="ser_mess">success</div>',
   'error' => $false,
   'error_msg' => array('empty' => '<div class="ser_mess">empty</div>',)
);

if(empty($_POST['input']) ){

$results['error'];
$results['error_msg']['empty'];


}else{

$results['success'];
$results['complete'];

}


echo json_encode($results);
exit();

3 个答案:

答案 0 :(得分:0)

success: function (data) {
    $('#form_response').html(data);
}

这个块是你的响应处理程序 - 而data是你从AJAX调用中获取的JSON对象。如果你想显示你的JSON对象的特定属性,你会想要引用类似data.complete的东西,它看起来像一点HTML,然后你可以把它放到your div#form_response

success: function (data) {
        $('#form_response').html(data.success);
}

您可以以相同的方式访问所有对象:

{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}

所以要获取“空”错误消息的html,你可以使用

$('#form_response').html(data.error_msg.empty);

或者,如果我误解了这个问题,如果你想让RAW json出现在div#form_response中,你可以将json对象转换为字符串:

json_string = JSON.stringify( data );
$('#form_response').html( json_string );

答案 1 :(得分:-1)

我相信这应该适合你:)

您的HTML / JS文件:

<script type="text/javascript" src="js/jquery.js"></script>

<div class="" id="form_response"></div>

<form id="add_property_form" action="" method="POST">
  <input type="text" name="input">
  <button type="submit">Send</button>
</form>

<script type="text/javascript">
$("#add_property_form").submit(function(evt){  

      evt.preventDefault();
      var formData = new FormData($(this)[0]);
   $.ajax({
       url: 'thescript.php',
       type: 'POST',
       data: formData,
       async: false,
       cache:false,
       contentType: false,
       processData: false,
       dataType: "json",

    success: function (data) {
    var resultData = data.response_msg; // get HTML to insert
    $('#form_response').html(resultData);
    // You can also use data.status (= true or false), to let you know which HTML was inserted :) 
    }

  });
return false;
});

</script>

您的PHP文件:

header('Content-Type: application/json');

// construct original array
$results = array(
   'status' => false,
   'response_msg' => ''
);

// analyze $_POST variables 
if(empty($_POST['input'])){ // if input post is not empty:
 $results['status'] = false; 
 $results['response_msg'] = '<div class="ser_mess">empty</div>';
}else{ // if input post is empty: 
 $results['status'] = true; 
 $results['response_msg'] = '<div class="ser_mess">success</div>';
}


echo json_encode($results); // encode as JSON
exit();

答案 2 :(得分:-1)

我的测试步骤与您的代码。解决问题。

  • 如果您使用ajax请求提交数据,那么您不希望本机提交表单。因此,只使用“按钮”类型的按钮,而不是“提交”类型。仅当表单应本地提交时才能正确使用evt.preventDefault();return false等语句(例如,不通过“提交”类型的按钮或类似提示),例如,您正在验证它。如果用户输入无效,则应用此类语句,以便可以停止提交表单。
  • 您的ajax无法启动,因为它未包含在$(document).ready(function () {...}
  • 我收到“TypeError:'append'调用未实现接口FormData 的对象。使用var formData = $('add_property_form').serialize();代替var formData = new FormData($(this)[0]);
  • async:false属性发出警告:“主线程上的同步XMLHttpRequest因其对最终用户体验的不利影响而被弃用。有关更多帮助http://xhr.spec.whatwg.org/ jquery-3.2.1 .min.js:4:15845" 。因此,请删除async。此外,您不需要cachecontentTypeprocessData。删除它们。
  • 因为通过设置dataType: "json",您已经告诉服务器您希望从服务器返回JSON编码数据,所以您不需要使用header('Content-Type: application/json');发送响应头。删除它。
  • 使用method: "post"代替type: "post",因为后者仅用于版本1.9.0的jquery。阅读ajax specification
  • if语句中的PHP代码容易出错。我用它制作了我的版本。
  • 如果您从服务器接收JSON编码数据,则无法直接将其作为html内容传递给div。您必须单独阅读其值并对其执行某些操作。比喻:在php中你也不能简单地写echo $results,因为那时你会收到Notice: Array to string conversion。客户端代码也一样。

test.php的

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title></title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $("#add_property_form").submit(function (evt) {
                    evt.preventDefault();
                    var formData = $('#add_property_form').serialize();

                    $.ajax({
                        url: 'thescript.php',
                        type: 'POST',
                        dataType: "json",
                        data: formData,
                        success: function (data, textStatus, jqXHR) {
                            var formResponse = $('#form_response');
                            var success = data.success;
                            var message = data.message;

                            if (success) {
                                formResponse.removeClass('error').addClass('success');
                            } else {
                                formResponse.removeClass('success').addClass('error');
                            }

                            formResponse.html(message);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log(jqXHR);
                        }
                    });
                    return false;
                });
            });
        </script>

        <style type="text/css">
            .success,
            .error {
                max-width: 400px;
                color: white;
                margin-bottom: 15px;
            }

            .success {
                background-color: green;
            }

            .error {
                color: white;
                background-color: red;
            }
        </style>
    </head>
    <body>

        <div id="form_response" class="message"></div>

        <form id="add_property_form" action="" method="POST">
            <input type="text" name="input">
            <button type="submit">Send</button>
        </form>

    </body>
</html>

thescript.php

<?php

if (empty($_POST['input'])) {
    $results['success'] = false;
    $results['message'] = 'No input value provided!';
} else {
    $results['success'] = true;
    $results['message'] = 'You provided the value ' . $_POST['input'];
}

echo json_encode($results);
exit();

另一个例子

由于您正在寻找一个完整的例子,我冒昧地为您创建一个。

它的主要观点是为ajax请求定义“错误”回调。因为,当你抛出错误时,你实际上希望你的ajax“错误”回调扮演它的角色。要激活它,您只需发送一个自定义响应标头 - 状态代码为类“4xx:客户端错误” - 从服务器(search.php)到客户端({{ 1}})。这样的标题使用如下:“亲爱的浏览器,我,服务器,我发送给你的回复:'HTTP / 1.1 420请提供城市。'如你所见,它的状态代码是420,例如4xx级。所以请在你的ajax请求的“错误”回调中如此善意并处理它“。这是List ofStatus Codes

您可以按原样运行代码。在文档根目录中创建一个文件夹,将文件粘贴到其中,然后让custom.js运行。

test.php的

test.php

的search.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <!-- CSS resources -->
        <link href="custom.css" type="text/css" rel="stylesheet" />

        <!-- JS resources -->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
        <script src="custom.js" type="text/javascript"></script>
    </head>
    <body>

        <div class="page-container">

            <form class="user-input">
                <div class="messages">
                    Here come the error/success messages
                </div>

                <div class="form-group">
                    <label for="city">City:</label>
                    <input type="text" id="city" name="city" placeholder="City">
                </div>

                <div class="form-group">
                    <button type="button" id="searchButton" name="submit" value="search">
                        Search
                    </button>
                </div>
            </form>

            <div class="cities">
                Here comes the list of the found cities
            </div>

        </div>

    </body>
</html>

custom.js

<?php

// Get the posted values.
$city = isset($_POST['city']) ? $_POST['city'] : '';

// Validate the posted values.
if (empty($city)) {
    /*
     * This custom response header triggers the ajax error because the status
     * code begins with 4xx (which corresponds to the client errors). Here is
     * defined "420" as the custom status code. One can choose whatever code
     * between 401-499 which is not officially assigned, e.g. which is marked
     * as "Unassigned" in the official HTTP Status Code Registry. See the link.
     *
     * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
     */
    header('HTTP/1.1 420 Please provide the city.');
    exit();
} /* Other validations here using elseif statements */

/* The user input is valid. */

/*
 * Perform the search operation in a database, for example, and get the data.
 * Here just an array simulating a database result set with two records.
 */

$foundCities = [
    [
        'name' => 'Athens',
        'isCapital' => 'is a capital',
    ],
    [
        'name' => 'Constanta',
        'isCapital' => 'is not a capital',
    ],
];

// Print the response.
$response = [
    'message' => 'Great. ' . count($foundCities) . ' cities were found.',
    'cities' => $foundCities,
];

echo json_encode($response);
exit();

custom.css

$(document).ready(function () {
    $('#searchButton').click(function (event) {
        ajaxSearch();
    });
});

function ajaxSearch() {
    $.ajax({
        method: 'post',
        dataType: 'json',
        url: 'search.php',
        data: $('.user-input').serialize(),
        success: function (response, textStatus, jqXHR) {
            /*
             * Just for testing: diplay the whole response
             * in the console. So look unto the console log.
             */
            console.log(response);

            // Get the success message from the response object.
            var successMessage = response.message;

            // Get the list of the found cities from the response object.
            var cities = response.cities;

            // Display the success message.
            displayMessage('.messages', 'success', successMessage);

            // Display the list of the found cities.
            $('.cities').html('');
            $.each(cities, function (index, value) {
                var city = index + ": " + value.name + ' (' + value.isCapital + ')' + '<br/>';
                $('.cities').append(city);
            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Handle the raised errors. In your case, display the error message.
            handleAjaxError(jqXHR);
        },
        complete: function (jqXHR, textStatus) {
            // ... Do something here, after all ajax processes are finished.
        }
    });
}

/**
 * Display a user message.
 *
 * @param selector string The jQuery selector of a message container.
 * @param type string The message type: success|danger|warning.
 * @param message string The message text.
 * @return void
 */
function displayMessage(selector, type, message) {
    $(selector).html('<div class="message ' + type + '">' + message + '</div>');
}

/**
 * Handle an error raised by an ajax request.
 *
 * If the status code of the response is a custom one (420), defined by
 * the developer, then the corresponding error message is displayed.
 * Otherwise, e.g. if a system error occurres, the displayed message must
 * be a general, user-friendly one. So, that no system-related infos will be shown.
 *
 * @param jqXHR object The jQuery XMLHttpRequest object returned by the ajax request.
 * @return void
 */
function handleAjaxError(jqXHR) {
    var message = 'An error occurred during your request. Please try again, or contact us.';

    if (jqXHR.status === 420) {
        message = jqXHR.statusText;
    }

    displayMessage('.messages', 'danger', message);
}