简体   繁体   English

一个带有JSON响应且传递对象的AJAX示例

[英]AJAX example with JSON Response with object being passed

I'm having a difficult time using AJAX to send an associative array to a php file. 我在使用AJAX将关联数组发送到php文件时遇到了困难。 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. 这是我的代码,可以通过输入标签的形式来制作数组,但是我不知道如何在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>

Here's my php code: 这是我的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);
?>

I also have a div with id=wines . 我也有一个id = wines的div。 It was another thing I forgot to show. 这是我忘记展示的另一件事。 That's where the data is being returned to and displayed without the name however. 那是数据返回并显示的地方,但没有名称。

Your jQuery code to collect the values is correct, although .serialize() will simplify it. 您的jQuery代码收集值是正确的,尽管.serialize()可以简化它。

To retrieve the values in PHP, it's the same as if the form were being submitted normally. 要检索PHP中的值,就像正常提交表单一样。 They're in $_GET['name'] and $_GET['address1'] . 它们位于$_GET['name']$_GET['address1'] theData is just the name of the Javascript variable containing the object, it's not a property name sent to PHP. theData只是包含对象的Javascript变量的名称,而不是发送给PHP的属性名称。

Sorry I'm on my phone so its a short answer but use serialize 抱歉,我在手机上,所以它的答案很短,但是请使用序列化

http://api.jquery.com/serialize/ http://api.jquery.com/serialize/

Example

    $('form').on('submit', function(){
      $data = $(this).serialize();
      //send via ajax
      return false;
    })

To send data: I'm assuming you want to send the results of your form? 发送数据:我假设您要发送表单结果? To do this, first you're going to need to add a submit button to your page. 为此,首先您需要在页面上添加一个提交按钮。 This should be placed in your form to submit the code. 这应该放在您的表单中以提交代码。

Second, it looks like you're missing the <div id="wine"> which you've referenced in the AJAX success response, so you're going to want to add that. 其次,您似乎缺少了在AJAX成功响应中引用的<div id="wine"> ,因此您需要添加它。

Try this you have to add button to your form to fire the action: 尝试此操作,您必须在表单中添加按钮以触发操作:

<script type="text/javascript">

$(document).ready(function(){
  $('#submit').live('click', function() {
      var theData = {};
      $(":input:not(:button)").each(
        function(index){  
            var input = $(this);
            theData[input.attr('name')] = input.val();
        }
      );
      $.ajax({
          url: "http://www.aberlechiropractic.com/modifydoctors3.php",
          data: theData,
          dataType: 'json',
          success: function(data)
          {
              $('#wines').html(''); // Clear #wines div
              $('#wines').append('Data Received: ' + data + '<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"/>
    <input type="button" id="submit" value ="send"/>
  </form>
</body>




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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM