我正在尝试向后端程序员编写的API发送仅包含一个参数的简单表单,他告诉我,我需要做的就是通过ajax通过POST将一个参数发送到给定的URL.
问题是我收到没有'Access-Control-Allow-Origin'标头错误.
我已阅读这个问题,并尝试实施第一个答案的解决方案,但没有成功.当我通过 hurl 测试API时,它没有问题.
这是我用来发送表格的代码
$( document ).ready(function() { $('.btnEnviar').click(function(){ $.ajax({ type: 'POST', url: 'xxxxx.xxx/subscribers/subscribeEmail', datatype: 'jsonp', async: true, success:function(){ try{ alert("ok"); }catch (e){ alert(e); } } }); }); });这是表格:
<form class="newsletter" method="post" action="xxxxx.xxx/subscribers/subscribeEmail"> <input type="text" placeholder="mail here!" class="input" name="email"> <input type="submit" class="send pull-right hidden" value="Subscribe me!" placeholder="Subscribe me!"> <span class="btnEnviar"><i class="fa fa-envelope"></i></span> </form>该过程中不应包含任何PHP.
关于我可能做错了什么的任何见解?
解决方案尝试将crossDomain: true和xhrFields: { withCredentials: true }添加到请求中:
$( document ).ready(function() { $('.btnEnviar').click(function(){ $.ajax({ type: 'POST', url: 'xxxxx.xxx/subscribers/subscribeEmail', datatype: 'jsonp', async: true, xhrFields: { withCredentials: true }, crossDomain: true, success:function(){ try{ alert("ok"); }catch (e){ alert(e); } } }); }); });请参见 api.jquery/jquery.ajax/
I am trying to send a simple form with only one parameter to an API made by my back-end programmer, he told me that all i need to do is to send the one parameter to a given URL via POST using ajax.
The problem is I get a No 'Access-Control-Allow-Origin' header is present error.
I've read through this question and tried to implement the first answer's solution with no success. When i test the API via hurl it works with no problem.
this is the code that i am using to send the form
$( document ).ready(function() { $('.btnEnviar').click(function(){ $.ajax({ type: 'POST', url: 'xxxxx.xxx/subscribers/subscribeEmail', datatype: 'jsonp', async: true, success:function(){ try{ alert("ok"); }catch (e){ alert(e); } } }); }); });And this is the form:
<form class="newsletter" method="post" action="xxxxx.xxx/subscribers/subscribeEmail"> <input type="text" placeholder="mail here!" class="input" name="email"> <input type="submit" class="send pull-right hidden" value="Subscribe me!" placeholder="Subscribe me!"> <span class="btnEnviar"><i class="fa fa-envelope"></i></span> </form>there shouldn't be any PHP involved in the process.
Any insights on what could I be doing wrong?
解决方案Try adding crossDomain: true and xhrFields: { withCredentials: true } to the request:
$( document ).ready(function() { $('.btnEnviar').click(function(){ $.ajax({ type: 'POST', url: 'xxxxx.xxx/subscribers/subscribeEmail', datatype: 'jsonp', async: true, xhrFields: { withCredentials: true }, crossDomain: true, success:function(){ try{ alert("ok"); }catch (e){ alert(e); } } }); }); });See api.jquery/jquery.ajax/
更多推荐
跨域请求的简单ajax POST
发布评论