POST后获取JSON结果

Getting JSON result after POST

本文关键字:结果 JSON 获取 POST      更新时间:2023-09-26

我目前正在尝试POST一个带有搜索输入的Submit表单,并通过JSON获得结果。所有项目都是一个Web应用程序,它在一些XML文件中搜索以获取POST结果。

我在index.html中的表单是这样开始的:

<form method="post" action="/results">

/results是一个页面,其中有纯文本的JSON结果

另一方面,在我的脚本中,我试图获得如下JSON结果:

$("#buttonid").on('click',function(){
    $.ajax({
        url:'/results',
        dataType: 'json',
        type: 'post',
        cache: false,
        success: function(data){
            $(data).each(function(index,value){
                console.log(value);
            });
        }
    });
};

我无法通过控制台看到结果。我能做什么?有什么建议可以解决我的问题吗?

编辑:

这不仅仅是一个简单的排版错误,我还解决了在表单中删除action="/results"并在ajax选项中添加data: $(this).serialize(),的问题。感谢@foxygen。

正如Amir所说,success拼写错误。但我补充了三件事,这将进一步帮助你。由于您正在张贴数据,因此在将选项传递给ajax函数时,需要将表单数据添加到data属性中。此外,添加error回调也是一种常见的做法。最后,您应该对事件调用preventDefault,这样页面就不会重新加载。

$('form').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'/results',
        dataType: 'json',
        data: $(this).serialize(),
        type: 'post',
        cache: false,
        success: function(data){
            $(data).each(function(index,value){
                console.log(value);
            });
        },
        error: function(xhr){
            console.log(xhr.responseText);
        }
    });
});

您有一个打字错误(success而不是succes):

$("#buttonid").on('click',function(){
    $.ajax({
        url:'/results',
        dataType: 'json',
        type: 'post',
        cache: false,
        success: function(data){
            $(data).each(function(index,value){
                console.log(value);
            });
        }
    });
});