【问题标题】:How can I send data use post by javascript without form?如何在没有表单的情况下通过 javascript 发送数据使用帖子?
【发布时间】:2018-09-18 09:33:28
【问题描述】:

我尝试这样:

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

从url中,可以使用get获取参数的值

但我想使用 post 更改它。我不希望 url 中存在该值

在没有表单标签的情况下如何通过javascript做到这一点?

【问题讨论】:

标签: javascript jquery html post get


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

        }
        else
        {

        }
    }
});

【讨论】:

    【解决方案2】:
    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)
        });
    

    【讨论】:

      【解决方案3】:

      当您将数据放入 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 p>

      createSessionVariable.php 上的代码

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

      现在您可以在所需的页面上使用会话变量。它将帮助您将变量传递到页面并在不使用表单标签的情况下重定向到页面。

      但这并不是编写代码的好方法,因为它会使您的网站容易受到攻击。你仍然可以使用它。

      【讨论】:

      • 我正在尝试做 $item = $_GET['item'];但只有“未定义的索引”
      【解决方案4】:

      可以使用Asynchrone Http请求,俗称Ajax请求。有几种方法可以做到这一点: Using plain 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({
       url: "http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09",
       cache: false,
       success: function(html){
          $("#results").append(html);
       }
      });
      

      我已将问题与每种方法的工作原理相关联。

      【讨论】:

        【解决方案5】:

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

        在后台使用表单标签始终是一种选择。

        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>

        【讨论】:

        • 你知道,对于那些不想使用 ajax 的人
        • 问题的最后一行是:How can I do it without form tag by javascript?
        【解决方案6】:

        here,jQuery的ajax可以为你POST和序列化你的查询参数:

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

        【讨论】:

        • 您能否添加一些上下文以使其更具教育意义?
        【解决方案7】:

        使用 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);
        

        【讨论】:

          猜你喜欢
          • 2016-12-14
          • 1970-01-01
          • 2017-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-25
          • 1970-01-01
          相关资源
          最近更新 更多