jQuery Ajax POST not working with MailChimp

穿精又带淫゛_ 提交于 2019-11-29 18:37:33

问题


I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.

   $(function(){
     $("a#test").click(function(e){
       e.preventDefault()  
       data = {
         "apikey" : "667378947", 
         "id" : "90298590285", 
         "email_address" : "test@getmoxied.net", 
         "output" : "json"
       }

  $.ajax({ 
    type: "POST",
    url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
    data: data,
    success: function(data){
      alert(data);
    },
    error: function(){
      alert("err");
    }
  })       
 });
});   

Im pulling my hair out on this one, any insight is greatly appreciated.

Thanks in advance,

JN


回答1:


The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.

All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.

The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.




回答2:


There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.

Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.

I wrote a jQuery plugin that uses this method, if that's useful at all

https://github.com/scdoshi/jquery-ajaxchimp




回答3:


e.preventDefault();
data = {
  "apikey" : "667378947", 
  "id" : "90298590285", 
  "email_address" : "test@getmoxied.net", 
  "output" : "json"
};

Could be? Semicolon is important. Hehe



来源:https://stackoverflow.com/questions/5188418/jquery-ajax-post-not-working-with-mailchimp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!