ajax成功重定向页面并填充来自

时间:2018-06-07 09:29:08

标签: javascript ajax

JavaScript:

$(document).on('click', '.edit', function(){
    var id = $(this).attr("id");


    $.ajax({
        url:"/fatch",
        method:'get',
        data:{FileId:id},
        dataType:'json',
        success:function(data)
        {

            location.href = "/edit";
            alert(data.fname); // it's working 
            $('#fname').val(data.fname); // didn't work 

        }
    })
});

查看页面:

<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                            <label>Father Name</label>
                            <input type="text" class="form-control has-feedback-left" placeholder="Father Name" name="fname" id="fname"required>
                            <span class="fa fa-file form-control-feedback left" aria-hidden="true"></span>
                        </div>

JavaScript在/fatch页面上运行。我想在/edit页面中填写父姓名(包含无处不在的JavaScript文件)。

但是,它没有填写父亲的名字。为什么会发生这种情况?如何解决?

1 个答案:

答案 0 :(得分:0)

应该有效,您在代码中有多个fname字段请验证。或者使用这个

console.log($('input[name="fname"]'))
$('input[name="fname"]').each(function(i){
  console.log(this)
  $(this).val(Math.random()+"iota")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                            <label>Father Name</label>
                            <input type="text" class="form-control has-feedback-left" placeholder="Father Name" name="fname" id="fname"required>
                            <span class="fa fa-file form-control-feedback left" aria-hidden="true"></span>
                        </div>
                        
                        <div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                            <label>Father Name</label>
                            <input type="text" class="form-control has-feedback-left" placeholder="Father Name" name="fname" id="fname"required>
                            <span class="fa fa-file form-control-feedback left" aria-hidden="true"></span>
                        </div>