简体   繁体   中英

Request failing with “No 'Access-Control-Allow-Origin' header”

I've created a form using Get Response (the email client) and am trying to use ajax on the form to create a custom success/fail message. The code works fine. However when I link the ajax to the form it stops working and I receive the below error message. Would appreciate any help.

Error: XMLHttpRequest cannot load https://app.getresponse.com/add_subscriber.html . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8888 ' is therefore not allowed access.

<form id="email-form-2" name="email-form-2" accept-charset="utf-8" action="https://app.getresponse.com/add_subscriber.html" method="post">
 <input type="text" placeholder="Your Name" name="name">
     <input type="text" placeholder="Your Email" name="email">
       <textarea placeholder="Your Message..." name="custom_comment"></textarea>
          <input type="hidden" name="campaign_token" value="XYZ" />
          <input type="submit" value="Send Message" data-wait="Please wait...">
        </form>
        <div>
          <p>Thanks for contacting us :)</p>
        </div>
        <div>
          <p>Darn. It didn't work. Give it another shot and see what happens :)</p>
        </div>

         <script type="text/javascript">
          $(function () {
           $('#email-form-2').submit(function (e) {
           e.preventDefault();
           $.ajax({
            url: this.action,
            data: $(this).serialize(),
            type: 'POST'
            }).done(function () { 
           $("#email-form-2+div.w-form-done").show();
           $("#email-form-2+div.w-form-fail").hide();
           $("#email-form-2").hide();
          })
           .fail(function () { 
           $("#email-form-2+div.w-form-done").hide();
           $("#email-form-2+div.w-form-fail").show();
           $("#email-form-2").show();
         });
       });
   });
</script>

Okay, I would suggest you to use cURL using any language you prefer in the server side. For now I can suggest you cURL and PHP. Try this in proxy.php :

<?php 
    // create curl resource 
    $ch = curl_init(); 

    // set url 
    curl_setopt($ch, CURLOPT_URL, "https://app.getresponse.com/add_subscriber.html");

    //return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);

    // output
    die($output);
?>

And now you can use proxy.php in your AJAX requests as it is in the same domain. You also have another way:

<?php
    die(file_get_contents("https://app.getresponse.com/add_subscriber.html"));
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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