簡體   English   中英

我如何通過JavaScript發送沒有表單的數據使用帖子?

[英]How can I send data use post by javascript without form?

我這樣嘗試:

window.location = '/admin/product?name='+name+'&category='+category+'&createdAt='+createdAt;

如果執行了該語句,則結果url如下所示:

http://my-app.test/admin/product?name = chelsea&category = 47&createdAt = 2018-04-09

從網址中,它可以使用get獲取參數的值

但是我想用post來改變它。 我不希望該值存在於網址中

沒有javascript的表單標簽怎么辦?

jQuery.ajax({
    url: '/admin/product',
    type: "post",
    data: { name, category, createdAt },
    dataType: "json",
    success:function(response)
    {
        if(response.result)
        {

        }
        else
        {

        }
    }
});
fetch(URL, {
        method: 'POST',
        body: JSON.stringify({
            name: 'asif',
            email: 'asif@gmail.com'
        })
    }).then((response) => {
        return response.json();
    }).then((response) => {
        Console.log(response)
    }).catch((err) => {
        Console.log(err)
    });

將數據放在URL中時,可以使用$ _GET或$ _REQUEST來獲取數據。 如果要使用$ _POST方法獲取數據,則需要傳遞的是使用post方法本身。 如果您使用的是JQuery。 我建議您使用$ .ajax方法將數據發送到所需的頁面。 但是您將不會被重定向到該頁面。

如果要發送數據到頁面並且還希望重定向到頁面以在同一頁面上進一步處理數據,則應選擇將數據放入$ _SESSION變量,然后重定向到頁面並使用$ _SESSION變量在那邊。

我將提供一個簡單的例子

將在您的主頁上使用AJAX

$.ajax({
    method:'post',
    url:'createSessionVariable.php',
    data:{data1:'dataOne', data2:'dataTwo'},
    success:function(){
        window.location.href='pageYouWantToGetRedirected.php';
    }
});

上面的代碼會將數據發送到頁面createSessionVariable.php ,您將在其中使用php創建會話變量,然后在成功后將您重定向到pageYouWantToGetRedirected.php

createSessionVariable.php上的代碼

$_SESSION['data1'] = $_GET['data1'];
$_SESSION['data2'] = $_GET['data2'];
echo "Done";

現在,您可以在所需的頁面上使用會話變量。 這將幫助您將變量傳遞給頁面,以及不使用表單標簽而將其重定向到頁面。

但這不是編寫代碼的好方法,因為它會使您的網站容易受到攻擊。 您仍然可以使用它。

請參閱此處 ,jQuery的ajax可以為您發布查詢並序列化您的查詢參數:

$.ajax({
  url: '/admin/product',
  data: { name, category, createdAt },
  type: "POST",

您可以使用Asynchrone Http請求,通常稱為Ajax請求。 有幾種方法可以做到這一點: 使用純Javascript

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
       if (xmlhttp.status == 200) {
           document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
       }
       else if (xmlhttp.status == 400) {
          alert('There was an error 400');
       }
       else {
           alert('something else other than 200 was returned');
       }
    }
};

xmlhttp.open("GET", "http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09", true);
xmlhttp.send();

或使用Ajax

$.ajax({
 url: "http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09",
 cache: false,
 success: function(html){
    $("#results").append(html);
 }
});

我已將問題與每種方法的工作原理很好地聯系了起來。

@CertainPerformance的答案更好,但這是我的答案。

在后台使用form標簽始終是一個選擇。

 document.getElementById("name").value="Chelsea"; document.querySelectorAll("form")[0].submit(); 
 <div style="display:none;"> <form action="product.php" method="post"> <input name="name" id="name"> <!--DO OTHER PARAMETERS--> </form> </div> 

使用javascript的XMLHttpRequest發送POST請求(沒有jQuery)

var http = new XMLHttpRequest();

var url = "/admin/product";
var params = 'name='+name+'&category='+category+'&createdAt='+createdAt;
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

暫無
暫無

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

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