如何在AJAX中输出Json数据

时间:2017-06-12 03:08:31

标签: javascript json ajax

在本机JS中,我只知道如何使用AJAX将PHP / mySql的结果输出到元素“some_id”,而不是Json Encode,就像这样:

<script>
function addItem(value) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("some_id").innerHTML = xmlhttp.responseText;
                                                                }
                                                 }
      xmlhttp.open("GET","some_php.php?q="+value,true);
      xmlhttp.send();
                 }
</script>

但是如果PHP / mySQL的结果是Json Encoded,我如何在AJAX中将它输出到“some_id”?

3 个答案:

答案 0 :(得分:1)

首先用JSON.parse()解析json:

如果您的回复如下:

zoo = {}

def main():
    print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
    total_money = 1000
    print ("You have " + str(total_money) + " to spend")
    cost(total_money)

def animal_cost(total_money):
        animal_type = raw_input("Please enter an animal:")
        print ("Animal Type Entered: " + str(animal_type))
        global animal_quantity
        animal_quantity = int(raw_input("Please enter quantity of animals:"))
        print ("Animal Quantity Entered: " + str(animal_quantity))
        if animal_type in zoo:
            zoo[animal_type] += animal_quantity
        else: zoo[animal_type] = animal_quantity

        while True:
            if animal_type == 'horse':
                return 50 * animal_quantity
            if animal_type == 'oxen':
                return 35 * animal_quantity
            if animal_type == 'mule':
                return 20 * animal_quantity
            else:
                cost(total_money)

def cost(total_money):
    costing = animal_cost(total_money)
    total_money -= costing
    if total_money <= 0:
        print ("No money left, resetting money to 1000.")
        total_money = 1000
        zoo.clear()

    print ("Cost of Animals: " + str(costing))
    print ("Remaining Balance:" + str(total_money))
    choice = raw_input("Do you want to buy any more animals?(Y/N):")
    if choice in('Y','y'):
        cost(total_money)
    elif choice in ('N','n'):
        choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
        if choice_2 in('zoo','Zoo'):
            print zoo
        choice_3 = raw_input("is everything correct?(Y/N):")
        if choice_3 in ('Y','y'):
            print ("Thank you for shopping!")
        elif choice in ('N','n'):
            print ("Restarting Transaction")
            zoo.clear()
            cost(total_money)


if __name__ == '__main__':
    main()

使用类似的东西:

{
    "response": "This is a test response"
}

答案 1 :(得分:0)

//some_php.php
$value = $_POST['value'];
echo json_encode($value);   //Convert data to json data


<script>
function addItem(value) {
    $.ajax({
        type: "POST",
        url: "some_php.php",
        dataType: 'json',
        data: {value: value},
        success: function(res) {
          console.log(res);   //res is in json, no need to convert it
        }
    });
}
</script>

答案 2 :(得分:0)

假设您已从MySQL数据库中获取数据。 Lemme举了几个字段的例子。

yourdata.php

// after fetch data from MySQL
$data = new stdClass( );
$data -> email = $row['email'];
$data -> phone = $row['phone_number'];
$data -> age = $row['age'];
echo json_encode( $data );

现在您的文件中有Ajax,

var xhttp = new XMLHttpRequest( );
// the rest of your code here as you have implemented it
// where you get response.text , do this
var data = xhttp.responseText;
var myData = data.toString( );
var jsonObject = JSON.parse( myData );
// you can obtain each value from the json object
document.getElementById( 'divEmail' ).innerHTML = jsonObject.email;
document.getElementById( 'divPhone' ).innerHTML = jsonObject.phone;

在JavaScript中解析数据之前对数据进行字符串化的原因是因为JavaScript倾向于不理解用PHP编码的json数据(我认为),因为这样做会在JavaScript中出错

var myData = JSON.Parse( xhttp.responseText );

我在旅行时回答这个问题,这就是为什么你在那里看到很多评论,希望这会有所帮助。