2015-12-06 53 views
0

您好我已經創建了一個從表單獲取數據的JSON對象,現在我想將它發佈到redmine API中。這是我迄今爲止所做的。如何將此輸出張貼到API

<script> 
 
// This is the creation of JSON object 
 
$.fn.serializeObject = function() 
 
{ 
 
    var o = {}; 
 
    var a = this.serializeArray(); 
 
    $.each(a, function() { 
 
     if (o[this.name] !== undefined) { 
 
      if (!o[this.name].push) { 
 
       o[this.name] = [o[this.name]]; 
 
      } 
 
      o[this.name].push(this.value || ''); 
 
     } else { 
 
      o[this.name] = this.value || ''; 
 
     } 
 
    }); 
 
    return {"project":o}; 
 
}; 
 

 
// This is the API linking and POSTING 
 

 
    $(document).ready(function(){ 
 
     $("#submit").on('click', function(){ 
 
      // send ajax 
 
      $.ajax({ 
 
       url: 'http://localhost/redmine/projects.json', // url where to submit the request 
 
       type : "post", // type of action POST || GET 
 
       dataType : 'jsonp', 
 
       headers: { 'X-Redmine-API-Key': 'admin' }, 
 
       data : JSON.stringify($('form').serializeObject()), // post data || get data 
 
       success : function(result) { 
 
        // you can see the result from the console 
 
        // tab of the developer tools 
 
        alert("Sucess"); 
 
        console.log(result); 
 
       }, 
 
       error: function(xhr, resp, text) { 
 
        console.log(xhr, resp, text); 
 
       } 
 
      }) 
 
     }); 
 
    }); 
 
</script>
<form action="" method="post"> 
 
First Name:<input type="text" name="name" maxlength="12" size="12"/> <br/> 
 
Last Name:<input type="text" name="identifier" maxlength="36" size="12"/> <br/> 
 
<!-- number:<input type="number" name="number" maxlength="36" size="12"/> <br/> --> 
 
<textarea wrap="physical" cols="20" name="description" rows="5">Enter your favorite quote!</textarea><br/> 
 
<p><input type="submit" /></p> 
 
</form>

的後不能正常工作。 JSON對象創建良好,將其傳遞給API是問題所在。我覺得問題就在這裏,

data : JSON.stringify($('form').serializeObject()), 

我如何通過以上數據所創建的JSON對象。謝謝

回答

1

您不能使用POST和自定義標題jsonpjsonp在不同域中工作的基本原理是插入一個<script>標籤,該標籤在完成後調用回調。

<script src="different.domain/api/projects.json?callback=done123"></script> 

function done123 (result) { 
    // do something with result 
} 

服務器(如果它支持jsonp電話),然後返回JavaScript(不JSON!),看起來像這樣:

done123({"name1":"val1","name2":{"name3":true,"name4":5}}) 

完成後它調用你的功能和工作原理跨域因爲它使用script標籤。

如果來自同一域該管理平臺運行運行腳本,改變dataType: 'jsonp'json。根據redmine期望您發送數據的方式(JSON-body與表單數據),您可能需要更改data值:

// When redmine API expects JSON post body 
data : JSON.stringify($('form').serializeObject()), 

// When redmine API expects multipart POST data 
data : $('form').serializeObject()