带Ajax的烧瓶

I'm really struggling to understand what's going on with my code. The goal is to take 2 strings and display the edit distance. The request and response must be sent as JSON objects

Here is my index.html file.

<html>
    <head>
        <meta charset="utf-8"/>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

        <script>

            $(document).ready( function() {
                $('#mainForm').click(function() {
                   var formdata = $("#mainForm").serialize();
                   console.log(formdata);
                   $.ajax({
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({string1: $('#string1').val(), string2: $('#string2').val()}),
                        dataType: 'json',
                        url: '/index',
                        success: function (e) {
                            console.log(e);
                            window.location = "/index";
                        },
                        error: function(error) {
                        console.log(error);
                    }
                    });

                });
            });
        </script>
    </head>

    <body>
        <h1>Compute Edit Distance</h1>
        <form  action="/index" method='post' name="mainForm" id="mainForm"> 
            String1: <input type="text" name="string1" id="string1"> 
            </br>
            </br>

            String2: <input type="text" name="string2" id="string2">  
            </br>
            </br>
            <button name = "submit" id = "submit" name="submit">submit</button> 
        </br>
        </br>
        <span id="editDistance">{{edit_distance}}</span>
        </form>
    </body>
</html>

Now, when I switch $('#mainForm').click to $('#mainForm').submit, no data is sent over. If I keep it as .click my controller receives the data in JSON form correctly, but this is not the behavior I want. The strings are sent over only when you click within the form, and the edit_distance does not display. If I switch it to on submit, content-type is application/x-www-form-urlencoded and I get a server error. Why is this happening? Also, how can I dynamically display the edit distance as I'm typing in the strings?

When I press the submit button, the request JSON data gets set to None. Here is my server code.

@app.route('/index', methods=['GET', 'POST'])
def index():

    edit_distance = 0

    if request.method == 'POST':
        print(request.content_type)
        data = request.get_json()
        string1 = data['string1']
        string2 = data['string2']
        print(string1, string2)
        edit_distance = get_edit_distance(string1, string2, len(string1),len(string2))
        print(edit_distance)



    response = make_response(render_template('index.html', edit_distance =     edit_distance))
    return response

1个回答


内容类型为application / x-www-form-urlencoded,因为提交请求在ajax .onsubmit执行之后仍然通过。 因此,您将看到交替的JSON和x-www-form-urlencoded请求。 要解决此问题,您可以取消默认的提交行为:</ p>

  //防止刷新页面中的表单提交
event.preventDefault();
</ code> </ pre>

关于如何动态更新它,您可以成功设置所需div的innerHTML,如下所示:</ p>

  document.getElementById(“ divId”)。innerHTML =“所需值”;
</ code> </ pre>
     </ div>

展开原文

原文

The content-type is application/x-www-form-urlencoded because the submit request still goes through after the ajax .onsubmit is executed. So you'll see alternating JSON and x-www-form-urlencoded requests. To address this you can cancel the default submit behavior:

//Prevent form submission from refreshing page
event.preventDefault();

As for how to dynamically update it, you can on success set the innerHTML of the desired div like so:

document.getElementById("divId").innerHTML = "desired value";

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐