2016-12-01 61 views
0

我有一個第三方CRM的Web服務。這是工作正常使用HTML表單後張貼到外部URL不工作用ajax和php捲曲

<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當我用ajax有錯誤消息

「否「訪問 - 捲曲後

控制允許來源標頭出現在所請求的資源」 這是我的代碼

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

而且PHP捲曲不工作

<?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); 
?> 

請幫助我如何解決這個問題

回答

1

出於安全原因,瀏覽器限制從腳本中發起跨域的HTTP請求。 (CORS)

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

資源使得跨來源的HTTP請求時,它從比所述第一資源本身用作所述一個不同的域請求資源。

服務器需要添加CORS標頭,POST和選項的迴應,以明確允許訪問的域名中,你所服務的頁面

例如

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