Javascript 如何在AJAX中从php数组接收json

Javascript 如何在AJAX中从php数组接收json,javascript,php,jquery,json,ajax,Javascript,Php,Jquery,Json,Ajax,我正在进行一个AJAX调用,并试图从数组json\u encode()接收json,但似乎不起作用。谢谢你的帮助 我没有发现任何错误,我检查了其他一些stackoverflow问题,但找不到完整的示例 问题是,当调用ajax并返回结果中的所有内容时,它将进入div(#form_response) 我使用下面的代码得到的响应是: {"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/

我正在进行一个AJAX调用,并试图从数组
json\u encode()
接收json,但似乎不起作用。谢谢你的帮助

我没有发现任何错误,我检查了其他一些stackoverflow问题,但找不到完整的示例

问题是,当调用ajax并返回
结果中的所有内容时,它将进入div(#form_response)

我使用下面的代码得到的响应是:

{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}
{“success”:true,“error”:false,“complete”:“success”,“error_msg”:{“empty”:“empty”}
HTML和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>

发送
$(“添加属性表单”).submit(函数(evt){
evt.preventDefault();
var formData=新formData($(此)[0]);
$.ajax({
url:'thescript.php',
键入:“POST”,
数据:formData,
async:false,
cache:false,
contentType:false,
processData:false,
数据类型:“json”,
成功:功能(数据){
$('form#u response').html(数据);
}
});
返回false;
});
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();
header('Content-Type:application/json');
$success=true;
$false=false;
$results=数组(
“成功”=>$success,
“完成”=>“成功”,
'error'=>$false,
'error\u msg'=>array('empty'=>'empty',)
);
if(空($_POST['input'])){
$results['error'];
$results['error_msg']['empty'];
}否则{
$results['success'];
$results['complete'];
}
echo json_编码($results);
退出();
此块是您的响应处理程序,
数据
是您从AJAX调用返回的JSON对象。如果要显示JSON对象的特定属性,您需要引用类似于
data.complete
,它看起来像一点HTML,然后可以将其放入
您的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>"}}
或者,如果我误解了这个问题,如果您希望原始json出现在
div#form_response
中,您可以将json对象转换为字符串:

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

我很有信心这对你会有用:)

您的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>

发送
$(“添加属性表单”).submit(函数(evt){
evt.preventDefault();
var formData=新formData($(此)[0]);
$.ajax({
url:'thescript.php',
键入:“POST”,
数据:formData,
async:false,
cache:false,
contentType:false,
processData:false,
数据类型:“json”,
成功:功能(数据){
var resultData=data.response\u msg;//获取要插入的HTML
$('form#u response').html(resultData);
//您还可以使用data.status(=true或false)让您知道插入了哪个HTML:)
}
});
返回false;
});
您的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();
header('Content-Type:application/json');
//构造原始数组
$results=数组(
“状态”=>false,
“回复信息”=>“
);
//分析$\u POST变量
if(空($_POST['input']){//如果input POST不是空的:
$results['status']=false;
$results['response_msg']='empty';
}else{//如果输入post为空:
$results['status']=true;
$results['response_msg']='success';
}
echo json_encode($results);//编码为JSON
退出();

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

  • 如果使用ajax请求提交数据,则不希望以本机方式提交表单。因此,只使用“按钮”类型的按钮,而不是“提交”类型的按钮。像
    evt.preventDefault()这样的语句
    返回false
    仅在本机提交表单时(例如,不通过“提交”或类似类型的按钮)才正确使用,例如,您正在验证表单。如果用户输入无效,则应用此类语句,以便停止表单提交
  • ajax不会启动,因为它没有包含在
    $(document).ready(function(){…}
  • 我收到对未实现接口FormData的对象调用的“TypeError:‘append’。请使用
    var FormData=$('add_property_form')。serialize();
    而不是
    var FormData=new FormData($(this)[0]);
  • async:false
    属性发出警告:“主线程上的同步XMLHttpRequest已被弃用,因为它会对最终用户的体验造成有害影响。有关更多帮助,请参阅jquery-3.2.1.min.js:4:15845。因此,请删除
    async
    。此外,您不需要
    缓存
    内容类型
    处理数据
    。请删除它们
  • 由于通过设置
    数据类型:“json”
    ,您已经告诉服务器您希望从服务器返回json编码的数据,因此不需要发送带有
    头('Content-Type:application/json');
    的响应头。将其删除
  • 使用
    方法:“post”
    而不是
    类型:“post”
    ,因为后者仅在jquery版本1.9.0之前使用。请阅读
  • if语句中的php代码很容易出错。我用它制作了我的版本
  • 如果您从服务器接收JSON编码的数据,则不能将其作为html内容直接传递到div中。您必须单独读取其值并对其进行处理。类似地,在php中,您也不能简单地编写
    echo$results
    ,因为这样您将收到
    注意:数组到字符串的转换使用客户端代码
test.php search.php
你得到的是JSON,那么问题出在哪里?你想把原始JSON字符串放入div#form#u响应中吗?我不应该这样做吗?你可以-这取决于你想让它做什么?我假设你想让JSON响应中的一小段HTML出现在div#form#u响应中?基于我的假设,我在下面发布了一个答案那么,您如何从
error\u msg获取消息呢<
<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>
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();
<!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>
<?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();
<!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>
<?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();
$(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);
}
body {
    margin: 0;
    padding: 20px;
}

.page-container {
    padding: 30px;
    background-color: #f4f4f4;
}

.messages {
    margin-bottom: 20px;
}

.message {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid transparent;
}

.success {
    color: #3c763d;
    border-color: #d6e9c6;
    background-color: #dff0d8;
}

.danger {
    color: #a94442;
    border-color: #ebccd1;
    background-color: #f2dede;
}

.warning {
    color: #8a6d3b;
    border-color: #faebcc;
    background-color: #fcf8e3;
}

form {
    width: 400px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: inline-block;
    min-width: 40px;
}

button {
    padding: 7px 10px;
    margin: 10px;
    display: block;
    color: #fff;
    font-size: 14px;
    border: none;
    background-color: #8daf15;
}