//创建json数据格式 var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }, { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }; //发送json数据 var url = "organizePeople.php?people=" + escape(people.toJSONString()); xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = updatePage; xmlHttp.send(null);
这种做法已经是可以了,但是传送的url参数可能会太长,因为json对象我们不肯定有多少数据
所以应该考虑用post,而放弃用get
var url = "organizePeople.php?timeStamp=" + new Date().getTime(); request.open("POST", url, true); request.onreadystatechange = updatePage; request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send(people.toJSONString());
application/x-www-form-urlencoded,它让服务器知道现在发送的是文本,正如它从常规的 HTML 表单中得到的一样。