2011-02-11 31 views
0

我有原型JS Ajax请求,基本上是这样的:翻译prototypejs Ajax请求的libcurl在C++

new Ajax.Request("http://www.example.com", { 
    method: 'post', 
    postBody: '{"params":{"first":"one", "second":"two"}}', 
    contentType: 'text/json' 
    requestHeaders: { 
     'Content-Length': 42 
    } 
    onComplete: function() {} 
}); 

我试着libcurl中像这样的:

struct curl_slist *slist = NULL; 
slist = curl_slist_append(slist, "Content-Type: text/json"); 
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com"); 
curl_easy_setopt(curl, CURLOPT_HEADER, slist); 
curl_easy_setopt(curl, CURLOPT_POST, 1); 
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 42); 
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, "{\"params\":{\"first\":\"one\", \"second\":\"two\"}}"); 

但在在服务器端,它不像原型实现那样识别后置主体。

我还没有能够取得任何进展,所以我希望这里有人能够提供我需要的见解。谢谢!

+0

有`,`在缺少你AJAX请求(在onComplete和requestHeader之前) – giraff 2011-02-21 08:22:37

回答

0

我怀疑Prototype检测到postBody是用JSON编写的,并在将它发送到服务器之前转换为URL-Encoding(而libcurl没有)。你可以安装Firebug来看看会发生什么。

尝试发送以下内容作为postBody/libcurl中:

params[first]=one&params[second]=two 
+0

Prototype将`postBody`视为一个字符串,根本不处理它,只是将它[直接传递给XHR对象](https://github.com/sstephenson/prototype/blob /1fb9728/src/ajax/request.js#L212)。如果需要,检查[`parameters`](http://api.prototypejs.org/ajax/)并将其转换为URL编码的字符串。 – clockworkgeek 2011-02-21 12:47:03

0

另一个想法是添加一个原型sends by default到libcurl的标题:

X-Requested-With: XMLHttpRequest 
X-Prototype-Version: (Prototype.Version) 
Accept: text/javascript, text/html, application/xml, text/xml, */*