小编Ben*_*Ben的帖子

jQuery - 检测隐藏输入字段的值更改

我有一个隐藏的文本字段,其值通过AJAX响应更新.

<input type="hidden" value="" name="userid" id="useid" />
Run Code Online (Sandbox Code Playgroud)

当这个值改变时,我想发出一个AJAX请求.任何人都可以建议如何检测变化?

我有以下代码,但不知道如何查找值:

$('#userid').change( function() {  
    alert('Change!'); 
}) 
Run Code Online (Sandbox Code Playgroud)

jquery hidden field onchange event-handling

253
推荐指数
5
解决办法
25万
查看次数

Node.js - 使用async lib - async.foreach和object

我正在使用节点async lib - https://github.com/caolan/async#forEach,并希望迭代一个对象并打印出它的索引键.一旦完成,我想执行回调.

这是我到目前为止,但'iterating done'从未见过:

    async.forEach(Object.keys(dataObj), function (err, callback){ 
        console.log('*****');

    }, function() {
        console.log('iterating done');
    });  
Run Code Online (Sandbox Code Playgroud)
  1. 为什么不调用最终函数?

  2. 如何打印对象索引键?

loops asynchronous object node.js node-async

52
推荐指数
1
解决办法
7万
查看次数

PHP - 通过file_get_contents发布JSON

我正在尝试将JSON内容发布到远程REST端点,但是"内容"值在传递时似乎是空的.正确接收所有其他标头等,并且Web服务使用基于浏览器的测试客户端成功测试.

我的语法是否存在问题,我指定了"内容"字段?

$data = array("username" => "duser", "firstname" => "Demo", "surname" => "User", "email" => "example@example.com");   
$data_string = json_encode($data);

$result = file_get_contents('http://test.com/api/user/create', null, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => array('Content-Type: application/json'."\r\n"
. 'Authorization: username:key'."\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n"),
'content' => $data_string)
)
));

echo $result;
Run Code Online (Sandbox Code Playgroud)

php rest post json file-get-contents

21
推荐指数
3
解决办法
3万
查看次数

ES6 Promises - 在promise链中调用同步函数

我正在尝试承诺,并有一个非常基本的问题!

在承诺链中,调用同步函数是不好的做法?例如:

.then(function(results) {

    if(checkIfResultInMemory(results) === true){
       return getTotalFromMemory()
    }

   return results;

  })
Run Code Online (Sandbox Code Playgroud)

或者我的同步函数是否应该重构以返回promises?

asynchronous node.js promise es6-promise

15
推荐指数
1
解决办法
2万
查看次数

使用socket.io配置Express 4.0路由

我创建了一个新的Express应用程序.它为我生成了app.js然后我创建了以下index.js引入socket.io:

var app = require('./app');
server=app.listen(3000);

var io = require('socket.io');
var socket = io.listen(server, { log: false });

socket.on('connection', function (client){
    console.log('socket connected!');
});
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议我如何访问路由文件中的socket.io?

作为参考,默认生成的app.js如下:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', …
Run Code Online (Sandbox Code Playgroud)

routes node.js express socket.io

10
推荐指数
2
解决办法
4万
查看次数

Node.js - 解析简单的JSON对象并访问键和值

我是Node的新手并且正在努力访问一个简单的JSON对象.我的request.body将具有类似于以下内容的JSON内容:

{
    "store_config": [
        {
            "name": "hello",
            "name2": "world"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

"store_config"值将始终存在,但其中的键和值可以是任何值.

如何迭代键和值来访问每个键?我还想以异步方式处理每个.

欣赏任何想法或方向.


UPDATE

console.log(typeof(request.body));
Run Code Online (Sandbox Code Playgroud)

返回: Object

parsedBody = JSON.parse(request.body);
Run Code Online (Sandbox Code Playgroud)

收益:

SyntaxError: Unexpected token o
    at Object.parse (native)
Run Code Online (Sandbox Code Playgroud)

更新2 - 进一步调试:

当我尝试遍历数组时,只有一个值:

request.body.store_config.forEach(function(item, index) {
  console.log(index);
  console.log(request.body.store_config[index]);

});
Run Code Online (Sandbox Code Playgroud)

收益:

0
{ name: 'hello', name2: 'world' }
Run Code Online (Sandbox Code Playgroud)

javascript json asynchronous object node.js

9
推荐指数
1
解决办法
6万
查看次数

Node.js - require未定义异常

我是一个完整的Node.js新手,并且在基础知识上苦苦挣扎.在服务器上运行此代码:

var http        = require("http"),
    sys         = require("util"),
    io          = require("socket.io"),
    GlobTrie    = require("glob-trie.js");
Run Code Online (Sandbox Code Playgroud)

在第一次要求时给我一个例外:

Uncaught ReferenceError: require is not defined
(anonymous function)
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

此致,本.

require node.js

8
推荐指数
1
解决办法
2万
查看次数

计算对象数组中的重复项

我在服务器端JS中有如下对象数组:

[
    {
        "Company": "IBM"
    },
    {
        "Person": "ACORD LOMA"
    },
    {
        "Company": "IBM"
    },
    {
        "Company": "MSFT"
    },
    {
        "Place": "New York"
    }
]
Run Code Online (Sandbox Code Playgroud)

我需要遍历这个结构,检测任何重复项,然后在每个值的旁边找到重复的计数.

这两个值必须匹配才能符合重复条件,例如"公司":"IBM"不匹配"公司":"MSFT".

如果需要,我可以选择更改对象的入站数组.我希望输出是一个对象,但我真的很难让它工作.

编辑:这是我到目前为止的代码,其中processArray是上面列出的数组.

var returnObj = {};

    for(var x=0; x < processArray.length; x++){

        //Check if we already have the array item as a key in the return obj
        returnObj[processArray[x]] = returnObj[processArray[x]] || processArray[x].toString();

        // Setup the count field
        returnObj[processArray[x]].count = returnObj[processArray[x]].count || 1;

        // Increment the count
        returnObj[processArray[x]].count = returnObj[processArray[x]].count + 1;

    }
    console.log('====================' …
Run Code Online (Sandbox Code Playgroud)

javascript arrays object count duplicates

6
推荐指数
1
解决办法
2万
查看次数

Node.js,Express,Mongoose - 输入验证 - 在路由或模型中?

我有一个接受JSON帖子的rest api资源.例:

{
"location": {
    "coordinates": [
        -122.41941550000001,
        37.7749295
    ]
}
Run Code Online (Sandbox Code Playgroud)

然后通过Express从请求中收集坐标:

module.exports.create = function(req, res, next) {

    var coordinates = req.body.location.coordinates;
    ....
Run Code Online (Sandbox Code Playgroud)

然后将它们提交给Mongoose模型.我正在编写测试,其中location.coordinates缺少例如

{
"foo": {
    "bar": [
        -122.41941550000001,
        37.7749295
    ]
}
Run Code Online (Sandbox Code Playgroud)

然后,在模型的验证部分中失败:

locationSchema.path('location.coordinates').validate(function(coordinates){
                                            ^
TypeError: Cannot call method 'validate' of undefined
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何验证输入是否正确?是否应该在到达模型之前在路线中完成,还是应该在模型中完成?任何如何例子也将被赞赏.

作为参考,Mongoose模型看起来像:

var locationSchema = new Schema({
    userid: { type: Number, required: true },
    location: {
        type: [{
            type: "String",
            required: true,
            enum: ['Point', 'LineString', 'Polygon'],
            default: 'Point'
        }], required: true,
        coordinates: { type: [Number], required:true } …
Run Code Online (Sandbox Code Playgroud)

validation mongoose node.js express

5
推荐指数
1
解决办法
2632
查看次数

Node.js - Socket.io客户端文件不由基本节点Web服务器提供

我是Node.js和Socket.io的新手.我已经构建了一个非常基本的Web服务器,但是在使用它时,我无法加载socket.io客户端文件(我得到了404).

我正在尝试使用此客户端代码:

<script src="/socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)

我的理解是Node应该选择并解决它?它在一个更简单的Web服务器示例上.

我的Web服务器示例未解析如下:

var server = http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        } …
Run Code Online (Sandbox Code Playgroud)

include node.js socket.io

4
推荐指数
1
解决办法
3964
查看次数