我希望有人能帮助我,因为我已经试了一整天了:( (新东西))
我有一个数据库mySQL,其中包含一个表"products“(两行:"id”和"stock“)。我希望我的ios5应用程序发送一个"id“,并接收该产品的”股票“。
在我的PHP代码中:
echo json_encode(array(
'id'=>$id,
'stock'=>$stock, ));我相信它会向我的应用程序发送一个JSON,我的应用程序在一个名为的函数中接收这个JSON:
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *responseStringWEB = [request responseString];
NSLog(@"STRING:: %@ \n", responseStringWEB); //3
NSDictionary *responseDict = [responseStringWEB JSONValue];
NSLog(@"DICT: %@ \n", responseDict); //3
NSString *id_producto = [responseDict objectForKey:@"id"];
NSString *stock = [responseDict objectForKey:@"stock"];
NSLog(@"ID: %@\n", id_producto); //3
NSLog(@"stock: %@", stock); //3
}检查我得到的控制台:
**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado
2011-12-26 18:58:57.170 CaeDeCajon[1998:16403] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x984aeb0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`DICT`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`ID`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`stock`**: (null)问题是:我不知道JSON将采用什么格式(数组,我应该如何解析NSstring responseStringWEB来获得这两个值( ID和股票)。似乎我从数据库中收到了它们,但我并没有把它们提取出来。
HELP :)谢谢,
编辑::
谢谢。这真的很有帮助。
这似乎与我在PHP代码中使用的多个echo有关。现在我只有一个echo,以json格式发送数据。它与我的数据库和应用程序完美配合:我接收所有项目的整个表格( "id“和"stock”)。谢谢。
但是我发现了另一个障碍(难怪),那就是我需要在产品售出后更改数据库,而且由于它们通常不会1-1出售,所以我的目的是发布受影响的产品/项目( array_id和array_reductor)的id和reductor(reductor代表该"id“的多少产品已售出)。
IOS5代码:
NSArray *array_id=[[NSArray alloc]initWithObjects:@"0",@"3",@"5", nil]; //使用id products;
NSArray *array_reductor=[[NSArray alloc]initWithObjects:@"10",@"5",@"40", nil];//用售出的产品数量(所以我必须将数据库中以前的库存编号减去这些,才能得到当前的库存编号)。
NSURL *url=[[NSURL alloc]initWithString:@"http://www.haveyourapp.com/promos/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:array_id forKey:@"id"];
[request setPostValue:array_reductor forKey:@"reductor"];
[request setDelegate:self];
[request startAsynchronous];我的PHP文件:
if (isset($_POST‘is’)&&isset($_POST‘’reductor‘)) //检查是否有数据{
$id = array(); // I create arrays
$reductor = array();
$id=$_POST['id']; // and store arrays in them ( At least is what I believe )
$reductor=$_POST['reductor'];
$connection = new createConnection(); //i created a new object
$connection->connectToDatabase(); // connected to the database
$connection->selectDatabase();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// Stock reduction in the items affected////////////////////////////////
$num=mysql_numrows($id);
$i=0;
$stock_anterior=array();
while ($i < $num) {
$query=" SELECT stock FROM productos WHERE id = $id[$i]";
$stock_anterior[$i] = mysql_query($query);
++$i;
}
$l=0;
$num2=mysql_numrows($id);
while ($l < $num2) {
$stock_reductor[$l] = $stock_anterior[$l] - $reductor[$l];
$query = "UPDATE productos SET stock = '$stock_reductor[$l]' WHERE id = $id[$l] ";
mysql_query($query);
++$l;
}
$connection->closeConnection();但是我的代码不工作,我不知道问题是在我的应用程序中还是在PHP文件中(很可能),但是我如何接收这两个数组并使用它们?
提前感谢
我花了很多时间在堆栈溢出上:非常有用!
发布于 2011-12-27 07:56:49
使用HTTPScoop等工具检查PHP脚本输出。根据包含行Connection establishedDatabase selected..和Connection closedDesconectado的控制台输出,我怀疑出了什么问题...
**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado看起来您已经从在JSON启动之前打印的脚本中获得了一些日志记录,这不被iOS端的JSON解析器接受。
发布于 2011-12-27 02:14:07
json_encode只处理UTF8编码的数据,所以当发现无效字符时,它会返回NULL。
检查您的数据是否以UTF-8编码。
还要检查您的文件是否使用了UTF-8。
Json_encode的替代方案:
// función interna: comprueba si un array es puro o no
// es puro si sus índices son: 0, 1, 2, ..., N
function aputio($a) {
$i=0;
foreach ($a as $n=>$v) {
if (strcmp($n,$i)) return(true);
$i++;
}
return(false);
}
// cambiar quotes, \n y \r para devolver cadenas válidas JSON
function qcl2json($qcl) {
return str_replace('"','\"',str_replace("\n",'\n',str_replace("\r",'\r',$qcl)));
}
// devolver variable en formato json
function ajson($av,$level=0,$utf8=false) {
if (($av===null) && !$level) return("null");
if (!is_array($av)) return (gettype($av)=="integer"?$av:'"'.($utf8?utf8_encode($av):$av).'"');
$isobj=aputio($av);
$i=0;
if (!$level) $e=($isobj?"{":"["); else $e="";
foreach ($av as $n=>$v) {
if ($i) $e.=",";
if ($isobj) $e.=(is_numeric($n) && !is_string($n)?$n:"\"".qcl2json($utf8?utf8_encode($n):$n)."\"").":";
if (!is_array($v)) {
if (is_bool($v)) $e.=($v?"true":"false");
else if ($v==NULL) $e.='""';
else if (is_int($v)||is_double($v)) $e.=$v;
else $e.='"'.qcl2json($utf8?utf8_encode($v):$v).'"';
} else {
$e.=(count($v)
?(aputio($v)
?"{".ajson($v,$level+1)."}"
:"[".ajson($v,$level+1)."]")
:"{}");
}
$i++;
}
if (!$level) $e.=($isobj?"}":"]");
return($e);
}如果可以使用UTF-8,请避免使用此函数。
发布于 2011-12-27 02:18:18
您的json编码是正确的,尝试将这一行添加到您的php脚本中,因为IOS可能对响应非常严格。
将以下代码添加到您的php脚本:
header('Content-type: application/json');除了该检查之外,您还在匹配您的参数的大小写。我看到你的php脚本发送了id,但看起来你的ios脚本正在寻找ID。
https://stackoverflow.com/questions/8638044
复制相似问题