weixin_33722405 2016-02-28 12:27 采纳率: 0%
浏览 24

发布数据以使用Ajax查看

I have a template 'mytemplae.pt':

function do_option_ajax() {

               var address = document.getElementById('url').value;
               $.ajax({
                   type: "POST",
                   url: "url_option",
                   data: JSON.stringify({url: $(address)}),
                   contentType: 'application/json; charset=utf-8',
                   dataType: 'json',
                   error: function () {
                       alert('error')
                   },
                   success: function (data) {
                       alert('Success');
                   }
               })
           }


<form method="post" action="index">
  <input type="url " name="url" id='url' size="100">
    <button id="2" formaction="url_option" onclick="do_option_ajax()">Confirm</button>
</form>

in .py file:

config.add_route('option', '/url_option')
@view_config(route_name='option', renderer='json', request_method='POST')
def option(request):
    url = request.params['url']
    # do something and create json_result
    return json_result

with these I want to send back json_result to the view and do something with it, but it returns an empty view with jsob obect printed: enter image description here

  • 写回答

1条回答 默认 最新

  • 游.程 2016-03-01 08:04
    关注

    You need to prevent the default form action from firing in Javascript. At the moment your onclick handler is invoked and a millisecond later the standard HTML form submit kicks in. The standard form submit receives the data from the server and displays it as a new page.

    To prevent this you need to do something like

    <form id="myform">
      <input type="url " name="url" id='url' size="100">
        <button id="2">Confirm</button>
    </form>
    
    
    $("#myform").on('submit', function (e) {
    
        var address = document.getElementById('url').value;
        $.ajax({
            type: "POST",
            url: "url_option",
            data: JSON.stringify({url: $(address)}),
            ...
        });
        e.preventDefault();
    });
    

    Note that I'm listening for the form submit event, not the button click, and also I removed action and method attributes from the form as they only do harm in this case.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿