簡體   English   中英

AJAX將對象數組發布到端點

[英]AJAX Post array of objects to endpoint

我正在嘗試將對象數組發布到API端點(onClick)但我不斷收到400 Bad Request錯誤。

我不確定自己在做什么錯,並希望在此問題上尋求幫助。

我的代碼如下:

$('#test-post').on('click', function() {

          var postData = [
            {
              "artist": "Artist Name",
              "title": "Artist Title",
              "genre": "string",
              "duration": "2:05",
              "url": "Artist url",
            },
            {
              "artist": "Artist Name",
              "title": "Artist Title",
              "genre": "string",
              "duration": "2:05",
              "url": "Artist url",
            }
          ];

          $.ajax({
            url: 'http://localhost:8000/api/endpoint',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            success: function(data) {
              console.log('Data has been posted');
              console.log(data);
            },
            error: function(err) {
              console.log(err.statusText);
            }
          });
        });

任何幫助將不勝感激。

謝謝

這是工作代碼。 似乎JQuery丟失了。

 $('#test-post').on('click', function() { var postData = [ { "artist": "Artist Name", "title": "Artist Title", "genre": "string", "duration": "2:05", "url": "Artist url", }, { "artist": "Artist Name", "title": "Artist Title", "genre": "string", "duration": "2:05", "url": "Artist url", } ]; $.ajax({ url: 'http://localhost:8000/api/endpoint', type: 'POST', dataType: 'json', data: {'params': JSON.stringify(postData)}, success: function(data) { console.log('Data has been posted'); console.log(data); }, error: function(err) { console.log("Error is: " + err.statusText); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test-post">Click me</div> 

端點URL包含以下簡單代碼。 這可行。 <?php echo $_POST['params']; ?>

如果您使用的是ASP .Net MVC,請檢查您是否使用了正確的過濾器,默認情況下對POST請求使用[HttpPost]會將其視為Get請求

[HttpPost]
public JsonResult endpoint()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM