2017-06-03 28 views
1

我目前正在PapaParser的javascript幫助下將csv文件解析爲JSON格式。我想將使用AJAX解析的JSON數據發送到RESTful服務,而RESTful服務又必須將數據發送到MySQL數據庫。從JavaScript發送JSON到REST並將內容添加到數據庫

我無法將數據發送到RESTful服務。

我的JavaScript代碼是:`

$('#submit').click(function() 
 
{ 
 
    $("input[type=file]").parse({ 
 
    config: 
 
    { 
 
     delimiter:",", 
 
     header: true, 
 
     dynamicTyping: true, 
 
     skipEmptyLines: false, 
 
     complete: function(result, file) 
 
     { 
 
     console.log("This file done:", file); 
 
     var emp=(JSON.stringify(result.data, null, 4)); 
 

 
     $.ajax({ 
 
     url: 'http://localhost:8100/department/v1', 
 
     data: result.data, 
 
     datatype : "application/json", 
 
     type: 'POST', 
 
     dataType: 'JSON', 
 
     success: function(returnObj) { 
 
      //FunctionDefinitionHere 
 
      console.log(result.data); 
 
     } 
 
     }); 
 
    } 
 
} 
 
}); 
 

 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title>Add Employee | Allowance Processing System</title> 
 
\t <script type="text/javascript" src="PapaParse/jquery-3.2.1.js"></script> 
 
<script type="text/javascript" src="PapaParse/jquery-3.2.1.min.js"></script> 
 

 
</head> 
 
<body> 
 
\t <p>Select an Excel Sheet with Employee Details</p> 
 
\t <br/> 
 
\t <form action="#" method="POST"> 
 
\t \t <input type="file" name="file" id="file" accept=".csv" /> 
 
\t \t <input type="submit" id="submit"> 
 
\t </form> 
 
\t <script type="text/javascript" src="parse.js"></script> 
 
<script type="text/javascript" src="PapaParse/papaparse.js"></script> 
 
<script type="text/javascript" src="PapaParse/papaparse.min.js"></script> 
 
</body> 
 
</html>

`

回答

0

你有2種dataType性質。我懷疑你想contentType是JSON這也需要您發送字符串化的數據

嘗試

$.ajax({ 
    url: 'http://localhost:8100/department/v1', 
    data: emp, // stringified json 
    contentType: "application/json", 
    type: 'POST', 
    dataType: 'JSON', 
    success: function(returnObj) { 
    //FunctionDefinitionHere 
    console.log(returnObj); 
    } 
}); 

還添加了一個錯誤處理程序,以幫助調試

+0

沒有工作。也增加了錯誤處理程序ajax調用每次都會失敗,而不是執行成功函數,它會進入錯誤塊。 –

+0

添加錯誤處理程序以獲取有關爲什麼請求失敗的更多詳細信息。還請檢查瀏覽器開發工具網絡中的實際請求,以查看正在發送的內容是預期內容和檢查狀態,響應正文等 – charlietfl

+0

請求標頭 接受:text/html,application/xhtml + xml,application/xml; q = 0.9, Cache-Control:max-image/webp,*/*; q = 0.8 Accept-Encoding:gzip,deflate,br Accept-Language:zh-CN,en-US; q = 0.8,en; q =年齡= 0 連接:保活 的Content-Length:13 內容類型:應用/ X WWW的窗體-urlencoded 主機:本地主機:8100 產地:HTTP://本地主機:8100 的Referer:HTTP: //localhost:8100/add_employee.html Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0(Windows NT 6.1; Win6 4; 64)爲AppleWebKit/537.36(KHTML,例如Gecko)鉻/ 58.0.3029.110 Safari瀏覽器/ 537.36 表單數據 視圖編碼 –

相關問題