简体   繁体   English

带有“ POST”的JSON Api调用

[英]JSON Api Call with “POST”

I try the following test-code to register a user at my Wordpress system (JSON Api User plugin is installed): 我尝试以下测试代码在我的Wordpress系统上注册用户(已安装JSON Api User插件):

<form id="register" name="register" method="post">
<input id="submitLogin" type="submit" value="Abschicken" onclick="register()">
</form>


<script type="text/javascript" charset="utf-8">


function register() {
 $.ajax({
url: 'http://XXX.de/api/user/register/?username=xxx@test.de&email=xxx@test.de&nonce=d60besdfee&display_name=xxx@test.de&user_pass=rtzrtzrtz0&apikey=gfhrtzh465&callback=?',
type: "POST",
dataType: 'json',
success: function(data){

 }
 });
}

</script>

What is wrong with the code? 代码有什么问题?

The problem is that the endpoint you're calling uses JSONP , not just JSON. 问题在于您正在调用的端点使用JSONP ,而不仅仅是JSON。 JSONP is a data format (JSON) and transmission mechanism (script element). JSONP是一种数据格式(JSON) 传输机制(脚本元素)。 It's inherently only GET, not POST, because under the covers what it really is is adding a script element to the page with a src attribute, which makes the browser get the script. 它本质上仅是GET,而不是POST,因为在幕后实际上是向页面添加具有src属性的脚本元素,这使浏览器可以获取脚本。

If the endpoint supports Cross-Origin Resource Sharing , you can use POST (you'll want to remove the callback=? part of the URL). 如果端点支持跨域资源共享 ,则可以使用POST(您将要删除URL的callback=?部分)。 If it doesn't, you cannot use POST to talk to that endpoint cross-origin because of the Same Origin Policy . 如果不是,则由于Same Origin Policy ,您无法使用POST与该端点交叉源对话。

Side note: I can't see any reason your call needs to use POST, as you're not sending any data (no data property in the options for the ajax call). 旁注:我看不到您的呼叫需要使用POST的任何原因,因为您没有发送任何数据( ajax呼叫的选项中没有data属性)。 You may simply want to remove the type: "POST" , change dataType: "json" to dataType: "jsonp" , and remove the &callback=? 您可能只想删除type: "POST" ,将dataType: "json"更改为dataType: "jsonp" ,并删除&callback=? (because jQuery will handle that when you specify dataType: "jsonp" ). (因为当您指定dataType: "jsonp"时,jQuery将处理该问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM