【问题标题】:Post some field values using ajax before submitting from submit button在从提交按钮提交之前使用 ajax 发布一些字段值
【发布时间】:2014-03-28 02:43:44
【问题描述】:

我可以在从提交按钮提交字段之前使用 ajax 发布一些值吗?

我正在使用以下代码。它取得了成功,但我无法获得发布的数据。 这有什么线索吗? 您的帮助/评论将不胜感激。谢谢!

function auto_fill(){  

        var that = $(this),
            url = './auto_fill.php',
            type = that.attr('method'),
            data = {};

        that.find('[name]').each(function(index,value){
            var that =$(this),
                name =that.attr('name'),
                value = that.val();
                data[name] = value;
        }); 

        $.ajax({
            url: url,
            type: type,
            data: data,
            success: function(response) {
                        document.getElementById("f_name").value="<?php echo $name ?>";
                        document.getElementById("phn_no").value="<?php echo $phn_num ?>";

            }
        });

        return false;
    }

【问题讨论】:

  • echo $name 仅适用于第一页加载,您应该使用您得到的响应来设置值
  • 什么响应返回服务器脚本?
  • auto_fill 怎么叫?
  • @juvian 我在 auto_fill.php 中使用了if(isset($_POST['id_num'])){ $name = Sam; },然后将其包含在我的 form.php 中,其中包含此表单。
  • 这是你想要做的吗? stackoverflow.com/questions/13366204/…

标签: javascript php jquery ajax forms


【解决方案1】:

试试这个

function auto_fill(){
  $.getJSON("./auto_fill.php?id_num=" + $("#id_num").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#f_name").val(item.value);
            } else if (item.field == "phonenum") {
              $("#phn_no").val(item.value); 
            } 
          });
        });
}

auto_fill.php

$id = $_GET['id_num'];

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => 'Your name'),

              array('field' => 'phonenumber', 
                    'value' => $phn),
              array('field' => 'somethinglikeDiscription', 
                    'value' => 'You entered ID as '.$id));
echo json_encode($json );

您可以通过此 JSON 数组将任何变量传递给此值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多