如何使用ajax从div标签发送数据而无需表单?

时间:2017-09-27 03:52:37

标签: javascript php jquery html ajax

我有一个div如下:

<div id="test-container">
   <div id="test-one">
      <p id="data">Example to send</p>
   </div>
</div>

我需要发送<p> "Example to send"内的内容 因为我可以发送它而不需要使用表单,只使用ajax,jQuery和PHP

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用以下方法获取p的内容:

var content = $("#data").html();

然后你可以用这种方式用ajax发送它:

$.post("url_to_some_file.php", content, function(response){
//Here you can get the response from the server
});

答案 1 :(得分:1)

你需要一个事件来首先触发ajax函数

$('#button').click(function(){
   var data = $('.data').html()
   $.ajax({
      url: 'url_to_server',
      data: data,
      type: 'POST',
      success: function(result){
         alert(result)
     }
  })
})

答案 2 :(得分:0)

var getdata = $("#data").html(); // get the text inside of the p tag

$.post("yourphpfile.php", {data: getdata}).done(function(r) {

    alert("Data sent!"); // show alert box after the query sent

});

通过PHP获取数据

<?php
 $data = $_POST['data'];


?>