抱歉这个愚蠢的问题,但我对此感到疯狂:(
我正在尝试通过 POST 将 json 从 iOs 前端发送到基于 symfony2 的服务器。
我不知道我做错了什么,但 POST 中没有任何内容。
这是前端代码:
NSMutableDictionary* objeto = [NSMutableDictionary dictionary];
[objeto setValue:[NSNumber numberWithInt:2] forKey:@"cliente"];
[objeto setValue:[NSNumber numberWithInt:3] forKey:@"usuario"];
[objeto setValue:[NSNumber numberWithInt:4] forKey:@"producto"];
[objeto setValue:[NSNumber numberWithInt:100] forKey:@"cantidad"];
NSLog(@"objeto %@", [objeto JSONRepresentation]);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:objeto options:kNilOptions error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON String: %@",jsonString);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"http://xxx.com/nueva_venta"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self]autorelease];
if(connection)
{
recibeData = [NSMutableData data];
}
例如,如果我在服务器端执行此操作:
/**
* Prueba de nueva venta
* @Route("/nueva_venta", name="nueva_venta")
* @Method("POST")
*/
public function nuevaVenta(){
$request= Request::createFromGlobals();
return new Response(json_encode($request->request->all()));
}
我得到一个空的 json :(
如果我改为通过 Javascript 发出请求,它可以正常工作:
$(document).ready(function() {
var venta=new Venta();
venta.cliente=10;
venta.usuario=1;
venta.producto=11;
venta.cantidad=100;
var capsulaJson={"cliente": venta.cliente,
"usuario":venta.usuario,
"producto":venta.producto,
"cantidad":venta.cantidad};
var json=capsulaJson.toString();
$.post("http://xxx.com/nueva_venta", json,
function (datos) {
if (datos) {
alert(datos);
}
else {
alert("No funciona :-(");
}
}
);
});
任何意见,将不胜感激。