使用ajax时php中未定义的索引

时间:2016-05-05 05:54:52

标签: javascript php html

我的表单页面:

<body>  
<head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
        function val()
        {
            var name=document.getElementById("name").value;
            if(name == '')
            {
                alert(name+" is empty");
            }
            else
            {
            var dataString = "name = "+name;
            $.ajax({
                type:"POST",
                url:"hi.php",
                data:dataString,
                cache:false,
                success:function(html){
                    $('#msg').html(html);
                }
            });
            }
        return false;
        }
        </script>

    </head>
<body>
    <form>
        <input type="text" id="name" >
        <br/><br/>
        <input type="submit" value ="submit" onclick="return val()">
    </form>
<p id="msg"></p>
</body>

这是我的hi.php文件

<?php
$name = $_POST["name"];
echo "Response : ".$name;
?>

点击提交按钮时会显示错误Notice: Undefined index: name in C:\wamp\www\SendEmailAjaxJquery\hi.php on line 2

我不知道错误plz在哪里帮助我找出错误......

提前致谢

3 个答案:

答案 0 :(得分:1)

用这个来代替这个

var dataString = "name = "+name;

更改为此

var dataString = 'name='+ name;

我有同样的情况,你会被引导。

 <html>
 <head>
  <script type="text/javascript" src="jquery-1.12.3.min.js"></script>
 </head>
 <body>
 <div class="content">
    <input type="text" class="search" id="searchid" placeholder="Search for    people" />
    <div id="result"></div>
 </div>  
 </body> 
 </html>
 <script type="text/javascript">
 $(function(){
  $(".search").keyup(function() 
  { 
    var searchid = $(this).val();
    var dataString = 'search='+ searchid;
    if(searchid!='')
    {
      $.ajax({
      type: "POST",
      url: "result.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
         $("#result").html(html).show();
      }
     });
   }return false;    
   });

答案 1 :(得分:1)

更改为:

$.ajax({
  type:"POST",
  url:"hi.php",
  data: {name: name},
  cache:false,
  success:function(html){
    $('#msg').html(html);
  }
});

jQuery ajax数据设置接受Object来自定义密钥。例如:

data: {anything: "123"}

在PHP中:

echo $_POST["anything"]; //123

答案 2 :(得分:0)