带有JSON响应且传递对象的AJAX示例 [英] AJAX example with JSON Response with object being passed

查看:106
本文介绍了带有JSON响应且传递对象的AJAX示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用AJAX将关联数组发送到php文件时遇到了困难.我有些不清楚的地方.这是我的代码,用于通过输入标签的形式制作数组,但是我不知道如何在php中发送和解释它.

I'm having a difficult time using AJAX to send an associative array to a php file. There's somethings I'm not understanding clearly. Here's my code to make the array from a form of input tags, but I don't know how to send it and interpret it in php.

<script type="text/javascript">
$(document).ready(function(){
  $(':submit').on('click', function() { // This event fires when a button is clicked
      var theData = {};
      $(":input:not(:button)").each(
        function(index){  
            var input = $(this);
            theData[input.attr('name')] = input.val();
        }
      );
      $.ajax({ // ajax call starts
          url: "http://www.aberlechiropractic.com/meningealrelease/modifydoctors/modifydoctors3.php",
          data: theData,
          dataType: 'json',
          success: function(data)
          {
              $('#wines').html(''); // Clear #wines div
              $('#wines').append('Data Received: ' + data.name+'   '+data.address + '<br/>');
          }
      });
      return false; // keeps the page from not refreshing 
  });
});
</script>

<body>
  <form>
    <input type="text" name="name" id="name" value="Jeff Aberle"/>
    <input type="text" name="address1" id="address1" value="4710 East Broadway"/>
    <button type="submit" name="updatedoctor" id="updatedoctor" value="all">All</button>
  </form>
</body>

这是我的php代码:

<?php
$name = $_GET['name'];
$address1 = $_GET['address1'];
$array = array($button, $address1);
print json_encode($array);
?>

啊,现在一切正常.我在这里编辑了所有代码以使其正常工作.

Ah now everything works. I edited all the code here to make this work.

<?php
// Get value of clicked button
$name = $_GET['name'];
$address1 = $_GET['address1'];
$array = array(
    "name"    => $name,
    "address"  => $address1,
);
print json_encode($array);
?>

我也有一个id = wines的div.这是我忘了展示的另一件事.那是数据返回并显示的地方,但是没有名称.

I also have a div with id=wines . It was another thing I forgot to show. That's where the data is being returned to and displayed without the name however.

推荐答案

尽管.serialize()将简化它,但您的jQuery代码收集值是正确的.

Your jQuery code to collect the values is correct, although .serialize() will simplify it.

要检索PHP中的值,就像正常提交表单一样.它们位于$_GET['name']$_GET['address1']中. theData只是包含对象的Javascript变量的名称,它不是发送给PHP的属性名称.

To retrieve the values in PHP, it's the same as if the form were being submitted normally. They're in $_GET['name'] and $_GET['address1']. theData is just the name of the Javascript variable containing the object, it's not a property name sent to PHP.

这篇关于带有JSON响应且传递对象的AJAX示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆