开发者

Troubles in getting a JSON object from a PHP page via NSURLConnection

开发者 https://www.devze.com 2023-02-15 01:18 出处:网络
I have a problem in my code and I can\'t figure out what\'s wrong with it. Perhaps I\'m doing some really stupid things I\'m not aware of, since I\'m a newbie in these topics.Here\'s the thing... Basi

I have a problem in my code and I can't figure out what's wrong with it. Perhaps I'm doing some really stupid things I'm not aware of, since I'm a newbie in these topics. Here's the thing... Basically, I'm trying to get a JSON object as a response from a PHP page on my web-server via a NSURLConnection. The PHP page retrieves some info from a DB and then encodes the JSON object, which is simply an array of four numerical strings, e.g., ["1","2","3","4"]. The relevant part of the PHP page is:

<?php 
include('mylib.php');
$id = $_GET["id"]; 
$db = connection();
$stmt = "SELECT col1,col2,col3,col4 FROM mytable WHERE `id` = " .$id;
$ris = mysql_query($stmt,$db);
if ($ris && mysql_num_rows($ris) == 1) {
    $arr = mysql_fetch_array($ris);
    header('Content-type: application/json'); 
    header("Content-Disposition: attachment; filename=res.json");  
    $json = json_encode(array($arr[0],$arr[1],$arr[2],$arr[3])); 
    echo $json;
?>    

While I'm getting the data I expect in the format I want when I download the开发者_开发百科 file from a browser, the JSON attachment file starts with an unwanted new line character: in this way, it appears the NSURLConnection stops immediately (I just get the '\n'). I'm not reporting the code for the networking part: it's very standard and it should be correct, since it works for other stuff I do... I tried to remove '\n' through:

$json = trim($json);

but it did't work. The new line is still there. Where does it come from? What should I do? Hope you guys can help me solve this issue... Thanks in advance!

EDIT

Ok! I don't have the new line char anymore (I removed a '\n' at the beginning of mylib.php), but I can't get the JSON object yet via NSURLConnection. It seems the method

connection:didReceiveData:

is never called now. But I don't have error in the connection: it simply receives 0 byte. Note that when I had the '\n' at the beginning, I received 1 byte. From a browser it works perfectly. What should I do?


I know this might sound obvious, but try looking in front of the opening <?php tag.

edit: or possibly at the end of "mylib.php".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号