如何使用ajax从html获取数据并将其传递到php

如何使用ajax从html获取数据并将其传递到php

问题描述:

我很想知道如何将字符串从表单传递到 php,该 php 将测试其中是否有内容,然后使用此表单发布警报消息以尝试从中获取数据,然后显示是否它被正确传递.

Hi I would love to know how can I pass the strings from a form to a php that will test if there is something in it and then post an alert message using this form to try and get data from it and then show if it was passed correctly.

HTML 代码:

<form action='' method=''>
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>

输出:

<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){

$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];

   if($a != NULL && $b != NULL && $c != NULL)
       {
         echo "
                <script type='text/javascript'>
                window.alert('Success'+ a + b + c)
                </script>
              ";
        }


};?>

虽然仍然在之前的同一页面中,但显示了我在警报框中输入的内容.

While still in the same page from before but shows what I have typed in there into the alert box.

如果它附带有关如何将其与 get 和 post 函数一起使用的说明以及链接(如果可以的话),我也将不胜感激?

I would also appreciate if it comes with instruction on how to use it with get and post functions and also with links if it can be done?

为了方便您可以对代码进行以下更改:

HTML:

<form action='' method='' id="myform">
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>

PHP:

(your_page_with_php_script)

(your_page_with_php_script)

<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){

$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];

   if($a != NULL && $b != NULL && $c != NULL)
   {
      echo "Success ".a." ".b." ".c;
   }


};
?>

脚本:(首先包含 jquery)

Script: (Include jquery first)

$('#myform').submit(function(){

var name = $('#name').val();
var age = $('#age').val();
var message = $('#message').val();


$.ajax({
  type: "POST",
  url: "your_page_with_php_script.php",
  data: "name="+name+"&age="+age+"&message="+message,
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

});