简体   繁体   English

ajax到php并从中获取JSON

[英]ajax to a php and get JSON from it

I have a php file that i connect to it with ajax and callback value is JSON when i get data from php it dosnt show and when alert data i see Object 我有一个php文件,我用ajax连接到它,回调值是JSON,当我从php获取数据时dosx显示,当警报数据我看到对象时

Where is my problem ? 我的问题在哪里?

PHP : PHP

if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){

    $query = mysql_query("select * from tab");

    for ($i=0;$i<mysql_num_rows($query);$i++){

         while($row = mysql_fetch_assoc($query)){
             $title['t'][i] = $row['title'];
             $title['d'][i] = $row['description'];
         }
    }

echo(json_encode($title));
exit();

?>

JS : JS

$('#button').click(function(){
    $.ajax({
        url : "test2.php",
        data : $("#tab"),
        type : "GET",
        success : function(b){
                      b = eval('('+ b +')');    
                      console.log((b['t']));
                      alert(b);
                  }
    });
});

How can i get all of data from this JSON and show me corect it ? 如何从这个JSON中获取所有数据并向我展示corect呢?

Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections. 这是一个完整的工作示例,包括单行提取和多行提取,不使用mysql_语法并使用预准备语句来阻止sql注入。

And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. 是的,不要使用mysql特定的语法,就像我在这里提到的: 我无法将表单数据导入数据库。 What am I doing wrong? 我究竟做错了什么?

function example()
{
    var select = true;
    var url = '../scripts/ajax.php';

    $.ajax(
    {
        // Post select to url.
        type : 'post',
        url : url,
        dataType : 'json', // expected returned data format.
        data : 
        {
                'select' : select // the variable you're posting.
        },
        success : function(data)
        {
            // This happens AFTER the PHP has returned an JSON array,
            // as explained below.
            var result1, result2, message;

            for(var i = 0; i < data.length; i++)
            {
                // Parse through the JSON array which was returned.
                // A proper error handling should be added here (check if
                // everything went successful or not)

                result1 = data[i].result1;
                result2 = data[i].result2;
                message = data[i].message;
                // Do something with result and result2, or message.
                // For example:
                $('#content').html(result1);

               // Or just alert / log the data.
               alert(result1);
            }
        },
        complete : function(data)
        {
            // do something, not critical.
        }
    });
}

Now we need to receive the posted variable in ajax.php: 现在我们需要在ajax.php中接收发布的变量:

$select = isset($_POST['select']) ? $_POST['select'] : false;

The ternary operator lets $select's value become false if It's not set. 如果没有设置,那么三元运算符会让$ select的值变为false。

Make sure you got access to your database here: 确保您可以访问您的数据库:

$db = $GLOBALS['db']; // An example of a PDO database connection

Now, check if $select is requested (true) and then perform some database requests, and return them with JSON: 现在,检查是否请求$ select(true)然后执行一些数据库请求,并使用JSON返回它们:

if($select)
{
    // Fetch data from the database.
    // Return the data with a JSON array (see below).
}
else
{
    $json[] = array
    (
        'message' => 'Not Requested'
    );
}
echo json_encode($json);
flush();

How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows. 如何从数据库中获取数据当然是可选的,您可以使用JSON从数据库中获取单行,也可以使用它返回多行。

Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)): 让我举一个例子,说明如何使用json返回多行(您将在javascript(数据)中迭代):

function selectMultipleRows($db, $query)
{
    $array = array();
    $stmt = $db->prepare($query);
    $stmt->execute();
    if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
    {
        foreach($result as $res)
        {
            foreach($res as $key=>$val)
            {
                $temp[$key] = utf8_encode($val);
            }
            array_push($array, $temp);
        }
        return $array;
    }
    return false;
}

Then you can do something like this: 然后你可以做这样的事情:

if($select)
{
    $array = array();
    $i = 0;

    $query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
    foreach(selectMultipleRows($db, $query) as $row)
    {
        $array[$i]["result1"] = $row['result1'];
        $array[$i]["result2"] = $row['result2'];
        $i++;
    }

    if(!(empty($array))) // If something was fetched
    {
        while(list($key, $value) = each($array))
        {
             $json[] = array
             (
                 'result1' => $value["result1"],
                 'result2' => $value["result2"],
                 'message' => 'success'
             );
       }
    }
    else // Nothing found in database
    { 
        $json[] = array
        (
             'message' => 'nothing found'
        );
    }
}
// ...

Or, if you want to KISS (Keep it simple stupid): 或者,如果你想KISS(保持简单愚蠢):

Init a basic function which select some values from the database and returns a single row: 初始化一个基本函数,从数据库中选择一些值并返回一行:

function getSingleRow($db, $query)
{
    $stmt = $db->prepare($query);
    $stmt->execute();
    // $stmt->execute(array(":id"=>$someValue)); another approach to execute.
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        $array = (
            'result1' => $result['result1'], 
            'result2' => $result['result2']
        );
        // An array is not needed for a single value.
        return $array;
    }
    return false;
}

And then fetch the row (or the single value) and return it with JSON: 然后获取行(或单个值)并使用JSON返回它:

if($select)
{
    // Assume that the previously defined query exists.
    $results = getSingleRow($db, $query);
    if($results !== false)
    {
         $json[] = array
         (
             'result1' => $results['result1'],
             'result2' => $results['result2'],
             'message' => 'success'
         );
    }
    else // Nothing found in database
    { 
        $json[] = array
        (
             'message' => 'nothing found'
        );
    }
}
// ...

And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text(). 如果你想获得$(“#tab”)的值,那么你必须做一些像$(“#tab”)。val()或$(“#tab”)。text()。

I hope that helps. 我希望有所帮助。

I suggest to use either: 我建议使用:

b = jQuery.parseJSON(data)

see more here or 在这里看到更多或

$.getJSON $ .getJSON

instead of eval() 而不是eval()

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

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