1

我是编程人员的新手,现在正在尝试使用 php 和 mysql 用于 IOS 应用程序的 Titanium mobile。

问题是,当我从 DB 获取一些数组数据并尝试传递给 Titanium 时,“this.responseText”包含“null”。

这是部分,

    loadReq.onload = function()  
    {  
        var json = this.responseText;
        var response = [];
        response = JSON.parse(json);
        Ti.API.info(response);
    };  

    loadReq.onerror = function(event)
    {
        alert("Network error");
        Ti.API.debug(event);
        Ti.API.info(event);
    };

    loadReq.open("POST","http://localhost/myAppName/post_loading.php");
        var params = {
            userid: win.userid
        };
        loadReq.send(params);

这是我的php代码。

    <?php
    $con = mysql_connect('localhost','root','root');
    if (!$con)
    {
        echo "Failed to connect.";
        exit;
    }
    $db = mysql_select_db('myAppName');
    if (!$db)
    {
        echo "Failed at selecting db.";
        exit;
    }

    $userid = $_POST['userid'];

    $sql = "here is sql order which will fetch array data based on $userid";
    $query = mysql_query($sql);
    $response = array();

    if (mysql_num_rows($query) > 0)
    {
        $row = mysql_fetch_array($query);
        $response = $row;
        echo json_encode($response);
    }
    else
    {
        echo "there is no such data"; 
    }
    ?>

php文件从数据库获取的数组数据是这样的,

    Array(
        [0] => Array(
                'id' => '1',
                'name' => 'name1',
                'sex' => 'm',
                'age' => '20'
               ),
        [1] => Array(
                'id' => '3',
                'name' => 'name3',
                'sex' => 'f',
                'age' => '25'
               ),
        [2] => Array(
                'id' => '5',
                'name' => 'name5',
                'sex' => 'm',
                'age' => '18'
               )
    )

我测试了一些案例,以确保 HTTPClient 工作正常,sql 顺序在语法上正确,并且能够正确传递单个数据(不是多维,而只是一个数组、值和单词)。

但是,目前还没有多维数组。Ti.API.info 只是告诉我响应是“null”

有什么建议吗?

提前致谢。

4

2 回答 2

0

请务必在回显 json 之前设置您的内容类型。在回声之前添加:

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

这会在 http 请求中设置一个标头,以便钛中的 javascript 引擎知道如何正确处理响应数据

于 2012-05-13T06:25:36.777 回答
0

我终于明白了。只需要在 php 中添加 foreach 函数,而不仅仅是一个回显。

所以答案是;

    foreach($responses as $response)
    {
            echo $response;
    }

这样一个简单的错误......花了足够长的时间:(希望这个问题可以节省很多其他人的时间。

于 2012-05-14T04:23:08.170 回答