我在使用某些脚本来通过AJAX执行功能而不刷新页面时遇到了问题。我有一个供用户输入外部URL的字段,当他们单击“提交”时,它会弹出一个模式窗口,其中包含通过单独的PHP页面(当前为images.php)生成的一些信息。当表单实际提交,页面重新加载并且images.php能够看到index.php?url =任何内容时,我都有脚本在工作,但是我试图更新页面而不必刷新。定义变量后是否需要重新渲染DIV?我认为这可能是我遇到问题的地方。

JS

<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {

var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
       type: "POST",
       url: url,
       data: {noteUrl: noteUrl},
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
     });

return false; // avoid to execute the actual submit of the form.
});
});
</script>


的HTML

<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>


PHP(除了提交给它的表单外,它还包含在模式中,该模式将打开,但在var_dump($ postUrl)上返回NULL)

$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;


我肯定会在这里遗漏一些明显的东西,但是说实话,我已经尝试过在这里可以找到的AJAX示例的每种组合。我是否错过了让PHP获取变量的重要步骤?我需要在某个地方刷新DIV吗?

请帮忙。

最佳答案

这是相同代码的更简洁版本,更正了缺少的引号。

$(function() {
    $("#newNote").submit(function() {
        $('#notePreview').empty();
        var url = "images.php"; // the script where you handle the form input.
        var noteUrl = $(this).find('#noteUrl').val();

        var request = $.ajax({
           type: "POST",
           url: url,
           data: {noteUrl: noteUrl}
        });

        request.done(function(data) {
           $('#notePreview').append(data);
        });

        return false; // avoid to execute the actual submit of the form.
    });
});

07-25 23:43
查看更多