简体   繁体   English

我如何通过JavaScript发送没有表单的数据使用帖子?

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

I try like this : 我这样尝试:

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

If the statement executed, the result url to be like this : 如果执行了该语句,则结果url如下所示:

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

From the url, it can use get to get the value of parameter 从网址中,它可以使用get获取参数的值

But I want to change it use post. 但是我想用post来改变它。 I don't want the value exist in the url 我不希望该值存在于网址中

How can I do it without form tag by javascript? 没有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)
    });

When you put the data in URL you can either use $_GET or $_REQUEST to get the data. 将数据放在URL中时,可以使用$ _GET或$ _REQUEST来获取数据。 In case you want to get the data using the $_POST method, you need to pass is using the post method itself. 如果要使用$ _POST方法获取数据,则需要传递的是使用post方法本身。 In case you are using JQuery. 如果您使用的是JQuery。 I'll suggest you to go for $.ajax method to send data to the page you want. 我建议您使用$ .ajax方法将数据发送到所需的页面。 But you will not be redirected to that page with it. 但是您将不会被重定向到该页面。

If in case you want to send the data to the page and also want to get redirected to the page for further processing of data on the same page, you should choose for putting the data into $_SESSION variables and then redirecting to the page and using the $_SESSION variable over there. 如果要发送数据到页面并且还希望重定向到页面以在同一页面上进一步处理数据,则应选择将数据放入$ _SESSION变量,然后重定向到页面并使用$ _SESSION变量在那边。

I'll provide a simple example 我将提供一个简单的例子

AJAX to be used on your main page 将在您的主页上使用AJAX

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

The above will send data to a page createSessionVariable.php where you will create session variables using php and then on success you will be redirected to pageYouWantToGetRedirected.php 上面的代码会将数据发送到页面createSessionVariable.php ,您将在其中使用php创建会话变量,然后在成功后将您重定向到pageYouWantToGetRedirected.php

Code on createSessionVariable.php createSessionVariable.php上的代码

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

Now you can use the session variables on the page you want. 现在,您可以在所需的页面上使用会话变量。 It will help you passing the variable to the page and redirecting to the page as well without using a form tag. 这将帮助您将变量传递给页面,以及不使用表单标签而将其重定向到页面。

But this is not considered a good way of writing code, as it can make your website vulnerable. 但这不是编写代码的好方法,因为它会使您的网站容易受到攻击。 Still you can use it. 您仍然可以使用它。

See here , jQuery's ajax can POST and serialize your query parameters for you: 请参阅此处 ,jQuery的ajax可以为您发布查询并序列化您的查询参数:

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

You can use Asynchrone Http request, commonly known as Ajax request. 您可以使用Asynchrone Http请求,通常称为Ajax请求。 There a few way to do this : Using plain Javascript : 有几种方法可以做到这一点: 使用纯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();

Or using Ajax 或使用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);
 }
});

I have linked question with good explaination on how each method works. 我已将问题与每种方法的工作原理很好地联系了起来。

@CertainPerformance's answer is better, but here's my answer. @CertainPerformance的答案更好,但这是我的答案。

Using the form tag in the background is always an option. 在后台使用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> 

use javascript's XMLHttpRequest to send a POST request ( no jQuery ) 使用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