【问题标题】:Embed Ajax requests in bind events (XHR)在绑定事件中嵌入 Ajax 请求 (XHR)
【发布时间】:2012-09-12 23:53:34
【问题描述】:

我正试图在某个地方找到答案,但我做不到,

所以我有一个 .bind() 事件,我想要什么时候触发,以便像 AJAX 一样使用 JSON 从 php 文件中进行获取查询。

我尝试了以下不起作用:

$(document).ready(function() {  
$("#adivhere").bind("valuesChanged", function(){ 

                            // Some variables here 
var max2 = 10
var min2 = 5

                            //The classic AJAX Request
function afunc(max2,min2){
var xmlhttp;  
if (window.XMLHttpRequest)
{   // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();  
}else  {    // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}


                           //The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){    

                         //The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/); 
var d = new Date(t[0], t[1], t[2]);
alert(d);   

}}  

                        //The XHR request with the .php file and the
                        // two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});

【问题讨论】:

    标签: php ajax json xmlhttprequest bind


    【解决方案1】:

    您的脚本中有几个“错误”:

    • "afunc" 从来没有被调用过,为什么要执行呢?
    • 括号没有正确闭合;最后缺少两个:)}

    【讨论】:

    • 谢谢。是的,它错过了一个})。那么如果我省略function afunc(max2,min2){ 并且相应的右括号会起作用吗?
    【解决方案2】:

    看起来你正在使用 jQuery,所以这应该可以工作:

    $(function(){
        $('#adivhere').bind('valuesChanged',function(){ 
            var max2 = 10;
            var min2 = 5;
    
            $.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
                alert(json);
    
                var t = json.date.split(/[-]/);
    
                if (t && t.length) {
                    var d = new Date(t[0], t[1], t[2]);
                    alert(d);
                }
            });
        });
    });
    

    jQuery 中已经有一个很棒的 $.getJSON 方法,它将为您完成所有繁重的工作,包括以 JSON 形式返回您的结果。

    您需要让您的 getdates.php 脚本回显 callback 并将结果包装在括号中,以便它作为实际的 jQuery 返回。

    【讨论】:

    • 谢谢。我认为这应该可行,但alert(json); 不会发生。目前getdates.php 回显了一个 Json 字符串,这是问题所在吗?上面的代码给出:getdates.php?callback=?max2=10&min2=5。我说的对吗?
    • @DDL449 需要触发您正在绑定的操作valuesChanged。我不认为valuesChanged 是默认操作,因此您需要将其更改为change 或在您想要的操作发生时使用$('#adivhere').trigger('valuesChanged'); 实际触发它。
    • @DDL449 实际上它应该转换为get dates.php?callback=?&max2=10&min2=5,其中第二个?将被jQuery自动替换为json_callback1283754914之类的东西。
    猜你喜欢
    • 2012-08-26
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多