2012-01-15 127 views
1

好吧,所以基本上我有一个变量在ajax中,我想发送到我的socket.io服务器来检查变量是否已经在json数组中。socket.io变量检查

的Ajax:

function isUniqueEmail(email) { 
    //email checking script here 
    $.get('info/mailcheck.js' + email, function(response) { 
     if(response == 1) { 
      alert("Your email is already on our list"); 
     } 

     else { 
      alert("We will add you shortly"); 
     };  
    }) 
}; 

JSON数组:

{"mail": 
[ 
    "[email protected]", 
    "[email protected]", 
    "[email protected]" 
]} 

的socket.io部分是其中IM困惑。基本上它只需要把变量(一个电子邮件)检查它是否已经在数组中,并返回1,如果是,或者返回0,如果不是,并将其写入数组中。

回答

0

我对node.js的了解不多,但可以使用如下所示的函数来检查值是否在数组中,如果不是,则将值推送到它。

function pushToArray(value, array) { 
    function inArray(val, arr) { 
     for (var i=0; i<arr.length; i++) { 
      if (arr[i] == val) { 
       return true; 
      } 
     return false; 
    } 
    if (inArray(value, array) { 
     return 1; 
    } else { 
     array.push(value); 
     return 0; 
    } 
} 
+0

它试图这样的事情,但就像我需要它太不写入JSON文件。 – lostAstronaut 2012-01-15 17:38:50

0

你对如何让它与socket.io一起工作或者如何在数组中找到元素感到困惑吗?如果您使用node.js,只需使用阵列。 的indexOf方法:

//obj = {"mail": ["[email protected]", "[email protected]"]} 
if (obj.mail.indexOf(email) != -1) { 
    //We have your email! 
} 
else { 
    //We don't 
} 
+0

基本上,我只是给了一部分的JavaScript还有其他东西在JavaScript文件中,如电子邮件验证等。但是它将变量发送到socket.io脚本的部分和脚本接受它是我困惑的地方。 – lostAstronaut 2012-01-15 17:50:22

+0

您是否将传统的ajax调用与socket.io混合?这是行不通的。为了在服务器上使用socket.io,您需要从客户端连接到它。请参阅http://socket.io/#how-to-use – 2012-01-15 18:14:39

+0

上的示例哦,所以我必须从输入字段获取数据海峡,而不是从ajax获取数据海峡。这就是说,然后我认为socket.io是能够写入JSON – lostAstronaut 2012-01-15 20:02:53