[Cppcms-users] Can't get correct response from json rpc server when using javascript
Brought to you by:
artyom-beilis
|
From: 刘怀宇 <mys...@gm...> - 2011-09-07 08:45:00
|
Hello
There is a json rpc example in cppcms project. Now I want to send json_rpc
request using javascript , but it doesn't work.
I found that the Content-Type field of the HttpRequest message must be
"application/json" for cppcms application ,otherwise I got error messages
as follows " invalid content type "
And I tested successfully by python(in tests dir) and curl command
1.python:
def test(name,A,B):
if A != B:
print "Error :" + name
print "-----Actual--"
print A,"---Expected--"
print B,"-------------"
sys.exit(1)
else:
print "Ok:"+name
def test_status(h,stat):
if h.status != stat:
print "Status mistmatch:",h.status,"!=",stat
sys.exit(1)
def test_valid(name,params,ans,method='POST'):
h=httplib.HTTPConnection('192.168.30.17:8080');
headers = {"Content-type": "application/json"}
h.request(method,'/rpc',params,headers)
r=h.getresponse()
test(name,r.read(),ans)
test_valid('sum','{"method" : "sum" , "params" : [ 1, 2 ], "id" :
1}','{"id":1,"error":null,"result":3}')
2.curl command:
curl -i -X POST --header "Content-Type:application/json" -d
'{"method":"sum","params":[1,2],"id":1}' http://192.168.30.17:8080/rpc
They both succeeded.
But I can't get correct response by using javascript.The following code has
been tested in IE8 , Chrome13 and firefox6.It only success in IE8.
var xhr = new XMLHttpRequest();
var rpcUrl = 'http://192.168.30.17:8080/rpc';
var postData = '{"method":"sum","params":[1,2],"id":1}';
xhr.open("post", rpcUrl, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
alert(xhr.responseText)
}
}
}
xhr.send(postData);
Maybe the problem is that I can't set the "Content-Type" as
"application/json" successfully in Chrome and Firefox.
Do you have any experience about ajax?
Or just give me an idea!
|