简体   繁体   English

提交没有表单的POST方法?

[英]Submit POST method without a form?

I need to make a button with a similar functionality to "Follow" buttons in social networks. 我需要制作一个功能类似于社交网络中“关注”按钮的按钮。 The thing is I need to refresh the page when the user clicks the button since the page content largely depends whether the user is following or not. 问题是,当用户单击按钮时,我需要刷新页面,因为页面内容在很大程度上取决于用户是否关注。

I could submit the "follow" with ajax and reload the page when ajax responds. 我可以使用ajax提交“关注”,并在ajax响应时重新加载页面。 Is it possible to submit data with POST without AJAX (like forms do)? 是否可以使用不带AJAX的POST提交数据(就像表格一样)?

With JQuery you can do something like 使用JQuery,您可以执行以下操作

$.post('pageurl.php', {"variable1": "Value1", "Variable2": "Value2"}, function(datareturn){});

And handle it from serverside like normal 然后像往常一样从服务器端处理它

$var1 = $_POST["varriable1"];

Depending on the amount of data to be submitted, a regular link can submit data as well. 根据要提交的数据量,常规链接也可以提交数据。

This, for example, submits the search term this and that 例如,这将提交搜索词this and that

https://www.google.com/search?q=this+and+that

you can create your form dynamically and then remove it: 您可以动态创建表单,然后将其删除:

function postjs (to,method, p) {
  var myForm = document.createElement("form");
  myForm.method=method;
  myForm.action = to ;
  for (var k in p) {
    var myInput = document.createElement("input") ;
    myInput.setAttribute("name", k) ;
    myInput.setAttribute("value", p[k]);
    myForm.appendChild(myInput) ;
  }
  document.body.appendChild(myForm) ;
  myForm.submit() ;
  document.body.removeChild(myForm) ;
}

and call it: 并称之为:

postjs('target.php','post',{field1:'value1',field2:'value2'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM