繁体   English   中英

AJAX发布请求和字符串连接

[英]AJAX post request and string concatenation

我正在使用jQuery / AJAX来发布请求。 我正在尝试从第一个文本框中获取输入,并将其与url连接起来,并在第二个文本框中显示结果。 例如,如果用户输入asdf则ajax函数将发布该帖子,结果将显示为http://www.example.com/sdf/ 我有两个问题,如前所述,我有一个ajax函数,它正在执行发布,但在html中没有显示结果(它确实在firebug控制台中显示)。 其次,如何将输入连接到url中。 现场现场

<script>
$(document).ready(function () {
    var timer = null;
    var dataString;

    function submitForm() {
        $.ajax({
            type: "POST",
            url: "/concatenate/index.php",
            data: dataString,
            dataType: "html",
            success: function (data) {
                $("#result").html(data);
            }
        });
        return false
    }
    $("#input").on("keyup", function() {
        clearTimeout(timer);
        timer = setTimeout(submitForm, 40);
        var input = $("#input").val();
       dataString = { input : input }
    })
});
</script>
</head>
<body>

<h1>Enter a word:</h1>

<form action="create_entry.php" method="post">
Input: <input type="text" id="input" name="zipcode"></br>
Concatenated Result: <input type="text" id="result" name="location" value="http//www.example.com/ /" readonly></br>
</form>

我建议您将参数传递给submitForm而不是使用全局变量存储数据。

要进行串联,可以使用.data()方法存储输入的原始值,并始终获取该原始值,然后向其添加新值。

 <!-- remove extra space and "/" -->
<input type="text" id="result" name="location" value="http//www.example.com/" readonly>

$(document).ready(function () {
    var timer = null;
   /* cache $("#result") and store initial url value*/
    var $result=$("#result");
     $result.data('url',$result.val());

    function submitForm( input ) {
        $.ajax({
            type: "POST",
            url: "/concatenate/index.php",
            data: {input:input},
            dataType: "html",
            success: function (data) {
                 /* new value from stored url and new user input*/
                var url=$result.data('url'),
                 newUrl= url+data;
                /* use val() not html() */
                $result.val(newUrl);
            }
        });
        return false
    }


    $("#input").on("keyup", function() {
        /* no point using "$("#input")" to search DOM again when already have "this"*/
        var input = $(this).val();
        clearTimeout(timer);
        timer = setTimeout(function(){
             submitForm(input) ;
        }, 40);


    })
});

它应该是

success: function (data) { 
    $("#result").val( 'http//www.example.com/'+data+'/'); 
}

责怪这个

success: function (data) {
                $("#result").html(data);
            }

对此

success: function (data) { 
        $("#result").attr('value','http//www.example.com/'+data+'/');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM