doutang3760
2017-02-02 09:59
浏览 134
已采纳

jQuery AJAX和PHP没有获取数据值

I am trying to fetch the values of the data variable passed with jQuery AJAX to a php page. How to solve it?

Below is the HTML page code:

<input id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>

On the button click this jQuery AJAX calls a php page:

 $.ajax({
     type: "POST",
     url: "jquery-ajax-hello.php",
     contentType: "application/json; charset=utf-8",
     data: '{"name":"' + $("#name").val() + '"}',
     success: function (result, status, xhr) {
         $("#message").html(result);
     },
     error: function (xhr, status, error) {
         $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
     }
 });

The PHP Page code is:

<?php
$name = $_POST['name'];
echo "Hello ".$name.", How are you ?"; 
?>

In the php page I am not able to fetch the data varaible 'name' value?

Please help?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试将使用jQuery AJAX传递的数据变量的值提取到php页面。 如何解决?

下面是HTML页面代码:

 &lt; input id =“name”placeholder =“输入你的 名称。”  /&gt; 
&lt; button id =“submit”&gt;提交&lt; / button&gt; 
&lt; div id =“message”&gt;&lt; / div&gt; 
   
 
 <  p>在按钮上单击此jQuery AJAX调用php页面: 
 
 
  $ .ajax({
 type:“POST”,
 url:“jquery-ajax-  hello.php“,
 contentType:”application / json; charset = utf-8“,
 data:'{”name“:”'+ $(“#name”)。val()+'“}}  ,
 success:function(result,status,xhr){
 $(“#message”)。html(result); 
},
 error:function(xhr,status,error){
 $(  “#message”)。html(“结果:”+状态+“”+错误+“”+ xhr.status +“”+ xhr.statusText)
} 
}); 
   
 
 

PHP页面代码是:

 &lt;?php 
 $ name = $ _POST ['name']; 
echo“你好 “。$ name。”,你好吗?“;  
?&gt; 
   
 
 

在php页面中,我无法获取数据变量'name'值?

请帮忙?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

  • dsilhx5830 2017-02-02 10:03
    最佳回答

    Your data should be an object, what you're passing is a string, so it should be

    data: {
        name: $("#name").val()
    },
    
    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题