dora1989 2012-03-12 07:20
浏览 43
已采纳

使用ASIFormDataRequest进行简单的mysql查询

I'm trying to use ASIFormDataRequest for iphone to get some values from my mysql database.

From the iphone I do this:

NSURL *url = [NSURL URLWithString: ServerApiURLGet]; 
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: url]; 
[request setDelegate:self]; 
[request setPostValue:@"james" forKey:@"name"];

The request is send to a php files, which does this:

$con = mysql_connect("host","user","password");
mysql_select_db("table", $con);

$name = mysql_real_escape_string($_GET['name']); 
$query = mysql_query("SELECT score FROM `active_users` WHERE `nickname` ='$name';"); 

$result = mysql_fetch_array($query); 

sendResponse(200, json_encode($result));

And the response function:

function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}

Back to the iphone, I try to read the information from the callback like this:

- (void)requestFinished:(ASIHTTPRequest *)request
{        
NSDictionary *responseDict = [[request responseString] JSONValue];

NSLog(@"responseString: %@", [request responseString]);
NSLog(@"responseHeaders: %@", [request responseHeaders]);
NSLog(@"responseDict: %@", responseDict );
}

But it doesn't work. I get the error:

2012-03-12 08:33:57.657 Test[1991:707] -JSONValue failed. Error is: Unexpected end of input
2012-03-12 08:33:57.659 Test[1991:707] responseString: 

2012-03-12 08:33:57.660 Test[1991:707] responseHeaders: {
Connection = close;
"Content-Type" = "text/html";
Date = "Mon, 12 Mar 2012 07:33:58 GMT";
Server = "Apache/2.2.6 mod_auth_kerb/5.3 PHP/5.2.17 mod_fcgid/2.3.6";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "PHP/5.2.17";
}
  2012-03-12 08:33:57.661 Test[1991:707] responseDict: (null)

Any help is very appreciated. Thanks

Edit:

Same result if I pass in a simple array:

    $newArray = array(
    "score1" => '1000', 
);

 sendResponse(200, json_encode($newArray)); 

Solved:

When I changed _GET to _POST, it works. Thanks

  • 写回答

1条回答 默认 最新

  • duancashi1362 2012-03-12 07:28
    关注

    You're just sending your result to the iPhone without JSON encoding it, so the JSONValue on the iPhone side fails to understand the result.

    Try something like;

    sendResponse(200, json_encode($result));
    

    to encode your result before sending it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化