7 ajax的使用

1 基本使用:

<script>

    $(function () {
        //ajax技术:在不重复页面的情况下,与页面进行局部更新
        //get()请求
        //第三方
        $.ajax({
            url:"https://devapi.qweather.com/v7/weather/now?location=101010100&key=b5eeebe629134e0d8f90e6c3f848811c",
            method:"get",
            success:function (res) {
                //json数据
                // console.log(res.code);
                var code = res.code;
                if (code === "200"){
                    var text = res.now.text;
                    $('#weather .cond_txt').html(text);
                }
            }
        })
        //post请求 伪代码
        $.ajax({
            url:"https://devapi.qweather.com/v7/weather/now",
            method: 'post',
            data:{
                username:'mimic',
                password:$('input[type=password]').val()
            },
            success:function (res) {
                //....
            }
        })
    })
</script>

2 基于ajax发送post请求,获取表单中的数据。

<form class="form-horizontal" id="addForm">
    {% csrf_token %}
    <div class="form-group">
        <label for="" class="col-sm-2 control-label">{{ field.label }}</label>
        <div class="col-sm-10">
            {{ field }}
            <span style="color: red">{{ field.errors.0 }}</span>
        </div>
    </div>
</form>
<button type="button" class="btn btn-primary" id="btnAddSubmit">提交</button>

<script>
    $(function () {
        $('#btnAddSubmit').click(function () {
            $.ajax({
                url: "{% url 'customer_charge_add' pk=pk %}",
                type: "POST",
                data: $('#addForm').serialize(), // 此方式,也可以把csrf_token传到后端
                dataType: "JSON",
                success: function (res) {
                    console.log(res)
                }
            })

        })
    })
</script>
posted @ 2022-08-05 17:27  角角边  Views(23)  Comments(0)    收藏  举报