簡體   English   中英

提交表單時如何發送JSON請求參數? (而不是$ .ajax請求)

[英]How to send JSON request parameters while submitting the form? (instead of $.ajax request)

提交表單時如何將JSON請求參數發送到服務器?

function fun2() {
alert("in fun2");
document.searchForm.action = "http://localhost:8080/DatasetRepo/rest/downloadZip?"+"{'datasets':['1'],'token':'myfirsttoken'}";
document.forms["searchForm"].submit();}      

失敗,並顯示不支持的媒體類型錯誤。

$.post( "test.php", { name: "John", time: "2pm" } ); 

要么

$.get( "test.php", { name: "John", time: "2pm" } ); 

使用serialize獲取表單數據,例如

var form=$('form[name=searchForm]');
$.post(url, form.serialize(),callback)

而不是以json的形式發送,而只是以querystring的形式發送。

function fun2() {
    document.searchForm.action = "http://localhost:8080/DatasetRepo/rest/downloadZip?datasets[]=1&token=myfirsttoken";
    document.forms["searchForm"].submit();
}  

然后,您要發布到的文檔將在$ _GET數組中具有值...

<?php
    print_r($_GET);
?>

這可能不是一個好方法,因為如果您想發送JSON,您還需要將Contetn-Type標頭設置為application/json以便接收服務器理解它沒有處理URL編碼的查詢字符串。您將擁有典型的表格帖子。 大多數瀏覽器尚不支持使用enctype="application/json"因為這仍只是HTTP規范的草稿部分。

使用JSON.stringify函數在ajax帖子中發送json,下面的代碼段可用於使用ajax發送數據。

var data = {
      one: 'first',
      two: 'second'
};

function formSubmit(url, data) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function () {
    ajaxCallback(xmlhttp);
  };
  xmlhttp.open("POST", url, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xmlhttp.send(JSON.stringify(data));
 }

 function ajaxCallback(xmlhttp) {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       var response = JSON.parse(xmlhttp.responseText);
      console.log(response);
    }
 }

希望這可以幫助。

您將需要將數據發布到PHP腳本,並使用curl來發送內容類型並發布數據。

如果您使用的是Java,則類似。 請參閱如何在Java中使用cURL?

無論哪種情況,您都不能直接從表單發送json內容類型,而需要使用服務器端腳本來實現您的目標。

希望能有所幫助。

暫無
暫無

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

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