php - 使用 ASIFormDataRequest 进行简单的 mysql 查询

标签 php iphone mysql xcode asiformdatarequest

我正在尝试使用 iPhone 的 ASIFormDataRequest 从我的 mysql 数据库中获取一些值。

在 iPhone 上我这样做:

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

请求被发送到 php 文件,其执行以下操作:

$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));

响应函数:

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;
}

回到iphone,我尝试从回调中读取信息,如下所示:

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

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

但是这不起作用。我收到错误:

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)

非常感谢任何帮助。谢谢

编辑:

如果我传入一个简单的数组,结果相同:

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

 sendResponse(200, json_encode($newArray)); 

已解决:

当我将 _GET 更改为 _POST 时,它起作用了。谢谢

最佳答案

您只是将结果发送到 iPhone,而没有对其进行 JSON 编码,因此 iPhone 端的 JSONValue 无法理解结果。

尝试类似的事情;

sendResponse(200, json_encode($result));

在发送结果之前对其进行编码。

关于php - 使用 ASIFormDataRequest 进行简单的 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9663087/

相关文章:

PHP OOP 关于引用

php - 使用 MySQL、PHP 和 xml 进行 Google map 搜索

iphone - 如何从照片库获取图像路径以及如何从iPhone照片库中检索图像?

ios - iOS 上的 Cocoa 图形/绘图框架

php - 如何使用准备好的语句按时间排序?

php - Linux 上的 SQL Server 2005 扩展

php - 如何减少 IF 语句的数量?

iphone - UITableView 像 Xcode 中的 gridview 一样吗?

mysql - 相似表上的查询性能差异很大?

mysql - 非常慢的 MySQL 子查询