ajax调用后没有返回任何内容

时间:2016-01-17 06:45:59

标签: php jquery ajax

下面是我的Php文件,在那里我使用.html调用另一个php文件,在提交按钮后获取一些数据:

index.html

另一个php文件是:

ajax

当我写一些文字并点击提交按钮时,输入字段的文本显示在url中,并且不会从另一个php文件中获取任何数据。为什么?任何人都可以给我一些线索或帮助吗?谢谢。

2 个答案:

答案 0 :(得分:0)

单击按钮后,表单已提交,您需要使用preventDefault()方法停止该行为。用以下内容替换脚本:

<script>

            $(document).ready(function(){

                $('.refresh').click(function(e){
                  e.preventDefault(); // this line will prevent submission of form
                  //  var formData = new FormData($(this)[0]);
                    //event.preventDefault();
                    $.ajax({
                        url:'ajax.php',
                        type:'POST',
                       // data:{roll:'rana'},
                        //async:false,
                        success:function(response){
                            alert(response);
                            //document.write(response);
                        },
                        cache:false,
                        contentType:false,
                        processData:false
                    });return fasle;
                });                               
});
        </script>

答案 1 :(得分:0)

您的ajax.php文件中没有收到任何POST数据,因为没有,您的ajax请求中的data对象为空并已注释掉。

与您期望的相反,您的表单值不能通过POST发送到您的PHP文件,类似于使用action="file.php method="post",因为在AJAX中您必须手动&#34;建立&#34; <{1}}对象作为POST请求发送。

以下是它的工作原理:

表单文件:

data

后端文件:

<form>
    <input placeholder="text here" id="string">
    <input type="submit" class="refresh" value="submit">
</form>

<script>
$(document).ready(function() {
    $('.refresh').click(function(e) {
    e.preventDefault();
        $.ajax(
        {
            url:'ajax.php',
            type:'POST',
            data:{
                string: $('#string').val()
            },
            success:function(response) {
                alert(response);
            }
        }
        );
    });
});
</script>

注意我是如何通过<?php echo $_POST['string']; ?> 而不是id命名输入的,并通过name检索该值,然后将其分配给$('#string').val(),并通过POST请求发送。string您应该对表单中的每个输入字段执行相同的操作。

另外,你不需要这些:

cache:false,
contentType:false,
processData:false

因为原因。

相关问题