Post 到外部 url 无法使用 ajax 和 php curl

Post to external url is not working using ajax and php curl

我有第三方 CRM 的网络服务。使用 html 形式 post

效果很好
 <form method='post' action='http://example.com/myservice/action'>
      <div id='JavascriptWarning' class='warningmessage'>Javascript must be enabled in order to complete this form</div>

      <span class='webformlabel'>Last Name</span>
      <input class='webforminput' name='LastName' type='text'><span class='mandatorymarker'>*</span><br>

      <span class='webformlabel'>First Name</span>
      <input class='webforminput' name='FirstName' type='text'><span class='mandatorymarker'>*</span><br>

<input class='submitbutton' type='submit' id='SubmitButton' value='Submit' disabled='true' onclick='return Validate();'/>
</form>

但我想在ajax或php curl post

中使用它

当我使用 ajax 时出现错误消息

“请求的资源上没有 'Access-Control-Allow-Origin' header” 这是我的代码

function StoreCRMData() {             
          $.ajax({                  
              type: "POST",
              url: "http://example.com/myservice/action",
              data:$('form').serialize(),
              success: function()
              {
                  return false;
              }
          });
      }

另外 PHP curl 不工作

<?php
function post_to_url($url, $data) {
   $fields = '';
   foreach($data as $key => $value) { 
      $fields .= $key . '=' . $value . '&'; 
   }
   rtrim($fields, '&');
   $post = curl_init();
   curl_setopt($post, CURLOPT_URL, $url);
   curl_setopt($post, CURLOPT_POST, count($data));
   curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
   $result = curl_exec($post);
   curl_close($post);
}

$data = array(
   "LastName" => "My First name",
   "FirstName" => "My Last name"

);
post_to_url("http://example.com/myservice/action", $data);
?>

请帮我解决这个问题

出于安全原因,浏览器限制 cross-origin 从脚本中发起的 HTTP 请求。 ( CORS)

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves.

服务器需要将 CORS headers 添加到 POST 和 OPTIONS 响应,以专门允许访问您在其中提供页面的域

例如

 Access-Control-Allow-Origin: *
 Access-Control-Allow-Methods: POST, GET, OPTIONS
 Access-Control-Allow-Headers: Content-Type