简体   繁体   English

执行ajax发布数据并在控制台日志中回显这些数据时出错

[英]Error in performing ajax post data and echoing those data on the console log

i was asked to perform ajax post data to the php script which will include the another script which perform sql connection to the database and get all data and convert data to json format. 我被要求对php脚本执行ajax发布数据,该脚本将包括另一个脚本,该脚本执行与数据库的sql连接并获取所有数据并将数据转换为json格式。 then the json data will be shown on the console. 然后json数据将显示在控制台上。 also i also was asked to modify the ajax to post the values such as name and the religion such as abdullah and muslim respectively.. I want to perform coding on the passwrapper to get and show data on the console.log.. in ajax.html 另外我还被要求修改ajax以分别发布诸如name和abdullah和muslim之类的宗教之类的值。我想在passwrapper上执行编码,以在ajax中获取并显示console.log ..上的数据。 html

   <html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script> 
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
    $.ajax({
        type: "post",
        url: "passwrapper.php",
        dataType: "json",
        data: {
            lastName: 'Abdullah',
            lastReligion: 'Muslim',
        },      
        success: function(data){
            console.log(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
            $('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
            console.log('jqXHR:');
            console.log(jqXHR);
            console.log('textStatus:');
            console.log(textStatus);
            console.log('errorThrown:');
            console.log(errorThrown);
        },

    });
};
</script>
</body>
</html>

in passwrapper.php 在passwrapper.php中

       <?php
include 'student.php';
executePass();

receivePost();
function receivePost()
{
    if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
    {
        //do nothing
    } 
    else 
    {
        echo '<script>console.log("Last='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';

    }
}

?>

in student.php 在student.php中

<?php
function executePass()
{

    $conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
    $db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');

    $result = mysqli_query($conn,"select * from student");
    $json_array = array();
    while ($row = mysqli_fetch_assoc($result))
    {
        $json_array[] = $row;
    }

    echo json_encode($json_array);
}
?>

my question is how to show all data on the console log and also show the post data on the console.log.. please do not modify the student.php... only modify the passwrapper.php 我的问题是如何在控制台日志上显示所有数据,以及在console.log上显示发布数据..请不要修改student.php ...仅修改passwrapper.php

This should output the data from both functions combined, as JSON which your ajax "success" function can log. 这应该将两个函数组合的数据输出为JSON,您的ajax“成功”函数可以记录该JSON。 Your existing code has an issue because one part of it tries to return JSON, and the other part tries to return a <script> block, which is not valid JSON, and also would likely not be executed by the browser anyway for security reasons. 您现有的代码存在问题,因为其中一部分尝试返回JSON,而另一部分尝试返回<script>块,该块不是有效的JSON,并且出于安全原因也可能不会被浏览器执行。

I've also modified the two functions so they return their output to the caller as PHP variables, rather than directly echo-ing JSON strings to the browser. 我还修改了这两个函数,以便它们将输出作为PHP变量返回给调用方,而不是直接将JSON字符串回显到浏览器。 This makes them more re-usable, and also makes it much simpler to then combine the results into a single coherent JSON object to output to the browser. 这使它们更具可重用性,并且使将结果组合到单个一致的JSON对象中以输出到浏览器的过程也更加简单。

The console.log(data); console.log(data); command in your existing ajax "success" function will take care of logging all the returned data to your browser console. 现有ajax“成功”功能中的命令将负责将所有返回的数据记录到浏览器控制台中。

$studentArr = executePass();
$postArr = receivePost();

echo json_encode(array("students" => $studentArr, "postvars" => $postArr));

function receivePost()
{
    if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
    {
        //do nothing
    } 
    else 
    {
        return array ("lastName" => $_POST["lastName"], "lastReligion" => $_POST["lastReligion"]);
    }
}

function executePass()
{

    $conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
    $db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');

    $result = mysqli_query($conn,"select * from student");
    $json_array = array();
    while ($row = mysqli_fetch_assoc($result))
    {
        $json_array[] = $row;
    }


    return $json_array;
}

Now, I don't know the exact structure of your "students" data, so I can't give you an exact example of the output you'll receive, but if I were to assume that your students table had 3 simple fields - "id", "firstname", and "lastname", and there were 4 rows in the table, you would get a final JSON output something like this: 现在,我不知道您的“学生”数据的确切结构,因此我无法为您提供您将收到的输出的确切示例,但是如果我假设您的学生表具有3个简单字段, “ id”,“ firstname”和“ lastname”,并且表中有4行,您将获得最终的JSON输出,如下所示:

{
    "students":
    [
        {
            "id": 1,
            "firstname": "firstname1",
            "lastname": "lastname1"
        },
        {
            "id": 2,
            "firstname": "firstname2",
            "lastname": "lastname2"
        },
        {
            "id": 3,
            "firstname": "firstname3",
            "lastname": "lastname3"
        },
        {
            "id": 4,
            "firstname": "firstname4",
            "lastname": "lastname4"
        }
    ],
    "postvars": {
        "lastName": "Abdullah",
        "lastReligion": "Muslim"
    }
}

You have a JSON object with two properties. 您有一个带有两个属性的JSON对象。 The "students" property contains an array of all the students in your table. “学生”属性包含表中所有学生的数组。 The "postvars" property is another object containing properties matching the two POST variables you wanted to capture. “ postvars”属性是另一个对象,其中包含与要捕获的两个POST变量匹配的属性。

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

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