猿问

JQuery 发布到 REST 服务

我在堆栈上查看了一堆不同的问答,但我似乎无法解决我的问题,为什么我的休息界面没有在按钮提交上被调用。如果你们能看看问题出在哪里,我将不胜感激。


目标是有一个表单输入值(现在它们是硬编码的,直到我让它工作),并提交以通过 REST 调用更改它们所在的数据库。


编辑:单击按钮时,控制台中没有错误,DB 中没有显示任何内容。


<?php 


    $id = "123456";

    $auth = "XYZ123"; //this will change daily

    $url = "http://update/this/id/$id"; //this will change based on user


?>


<script >

    const URL = <?php echo json_encode($url);?>;

    const auth = <?php echo json_encode($auth);?>;

    const data = {

        "flag":"Y" //in the database flag has a value of N want to change to Y

    }


    $.ajaxSetup({

        headers: {

            'auth-key': '${auth}',

            'api-version': '1.0',

            'Content-Type': 'application/json',

            'Accepts': 'application/json',

            'Verbosity' : '4'

        }

    });

    $('.btn').click(function(){

        $.post(URL, data, function(data, status){

            console.log('${data} and status is ${status}')

        });

    })

</script>


<button type="submit" class="btn">Send it!</button>


潇湘沐
浏览 136回答 1
1回答

胡说叔叔

JavaScript 在 DOM 加载之前执行(<script>标签会中断 DOM 解析器)。到脚本执行时,还没有.btn元素。任何一个将脚本移动到正文的末尾(或至少在提交按钮之后),或在加载 DOM 后添加事件侦听器,或使用全局事件侦听器$(document).on('click',&nbsp;'.btn',&nbsp;function()&nbsp;{&nbsp;...&nbsp;}
随时随地看视频慕课网APP
我要回答