728x90

Node.js has generally caused two reactions in people I've introduced it to. Basically people either "got it" right away, or they ended up being very confused.

If you have been in the second group so far, here is my attempt to explain node:

  • It is a command line tool. You download a tarball, compile and install the source.
  • It let's you run JavaScript programs by typing 'node my_app.js' in your terminal.
  • The JS is executed by the V8 javascript engine (the thing that makes Google Chrome so fast).
  • Node provides a JavaScript API to access the network and file system

"But I can do everything I need in: ruby, python, php, java, ... !".

I hear you. And you are right! Node is no freaking unicorn that will come and do your work for you, sorry. It's just a tool, and it probably won't replace your regular tools completely, at least not for now.

"Get to the point!"

Alright, I will. Node is basically very good when you need to do several things at the same time. Have you ever written a piece of code and said "I wish this would run in parallel"? Well, in node everything runs in parallel, except your code.

"Huh?"

That's right, everything runs in parallel, except your code. To understand that, imagine your code is the king, and node is his army of servants.

The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work.

Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out.

Life is good, for the king's servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus. *

"That's fantastic, but could you quit the silly metaphor and speak geek to me?"

Sure. A simple node program may look like this:

var fs = require('fs')
  , sys = require('sys');

fs.readFile('treasure-chamber-report.txt'function(report) {
  sys.puts("oh, look at all my money: "+report);
});

fs.writeFile('letter-to-princess.txt''...'function() {
  sys.puts("can't wait to hear back from her!");
});

Your code gives node the two tasks to read and write a file, and then goes to sleep. Once node has completed a task, the callback for it is fired. But there can only be one callback firing at the same time. Until that callback has finished executing, all other callbacks have to wait in line. In addition to that, there is no guarantee on the order in which the callbacks will fire.

"So I don't have to worry about code accessing the same data structures at the same time?"

You got it! That's the entire beauty of JavaScripts single-threaded / event loop design!

"Very nice, but why should I use it?"

One reason is efficiency. In a web application, your main response time cost is usually the sum of time it takes to execute all your database queries. With node, you can execute all your queries at once, reducing the response time to the duration it takes to execute the slowest query.

Another reason is JavaScript. You can use node to share code between the browser and your backend. JavaScript is also on its way to become a really universal language. No matter if you did python, ruby, java, php, ... in the past, you've probably picked up some JS along the way, right?

And the last reason is raw speed. V8 is constantly pushing the boundaries in being one of the fastest dynamic language interpreters on the planet. I can't think of any other language that is being pushed for speed as aggressively as JavaScript is right now. In addition to that, node's I/O facilities are really light weight, bringing you as close to fully utilizing your system's full I/O capacities as possible.

"So you are saying I should write all my apps in node from now on?"

Yes and no. Once you start to swing the node hammer, everything is obviously going to start looking like a nail. But if you're working on something with a deadline, you might want to base your decision on:

  • Are low response times / high concurrency important? Node is really good at that.
  • How big is the project? Small projects should be fine. Big projects should evaluate carefully (available libraries, resources to fix a bug or two upstream, etc.).

"Does node run on Windows?"

No. If you are on windows, you need to run a virtual machine (I recommend VirtualBox) with Linux. Windows support for node is planned, but don't hold your breath for the next few months unless you want to help with the port.

"Can I access the DOM in node?"

Excellent question! No, the DOM is a browser thingy, and node's JS engine (V8) is thankfully totally separate from all that mess. However, there are people working on implementing the DOM as a node module, which may open very exciting possibilities such as unit testing client-side code.

"Isn't event driven programming really hard?"

That depends on you. If you already learned how to juggle AJAX calls and user events in the browser, getting used to node shouldn't be a problem.

Either way, test driven development can really help you to come up with maintainable designs.

"Who is using it?"

There is a small / incomplete list in the node wiki (scroll to "Companies using Node"). Yahoo is experimenting with node for YUI, Plurk is using it for massive comet and Paul Bakaus (of jQuery UI fame) is building a mind-blowing game engine that has some node in the backend. Joyent has hired Ryan Dahl (the creator of node) and heavily sponsors the development.

Oh, and Heroku just announced (experimental ) hosting support for node.js as well.

"Where can I learn more?"

Tim Caswell is running the excellent How To Node blog. Follow #nodejs on twitter. Subscribe to the mailing list. And come and hang out in the IRC channel, #node.js (yes, the dot is in the name). We're close to hitting the 200 lurker-mark there soon : ).

I'll also continue to write articles here on debuggable.com.

That's it for now. Feel free to comment if you have more questions!

--fg

*: The metaphor is obviously a simplification, but if it's hard to find a counterpart for the concept of non-blocking in reality.

728x90

Description: Load data from the server and place the returned HTML into the matched element.

Note: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of arguments passed to it.

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success)except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

1
$( "#result" ).load( "ajax/test.html" );

If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent.

Callback Function

If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.

1
2
3
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});

In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.

Request Method

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Loading Page Fragments

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

1
$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html><title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

1
$( "#a" ).load( "article.html" );

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

1
$( "#b" ).load( "article.html #target" );

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Examples:

Load another page's list items into an ordered list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Projects:</b>
<ol id="new-projects"></ol>
<script>
$( "#new-projects" ).load( "/resources/load.html #projects li" );
</script>
</body>
</html>

Demo:

Display a notice if the Ajax request encounters an error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>
<script>
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
</body>
</html>

Demo:

Load the feeds.html file into the div with the ID of feeds.

1
$( "#feeds" ).load( "feeds.html" );

Result:

1
<div id="feeds"><b>45</b> feeds found.</div>

pass arrays of data to the server.

1
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.

1
2
3
$( "#feeds" ).load( "feeds.php", { limit: 25 }, function() {
alert( "The last 25 entries in the feed have been loaded" );
});


728x90
안녕하세요 
100.123456를 
100.12와 같이 소수둘째자리까지만 표현하고 그뒤로는 모두 버리려구 합니다. 

round함수를 이용해서 아래와 같이 하면 반올림은 되는데 
round(100.123456,2) 


floor(100.123456,2) 와같이 하였더니 에러나 나네요. 

검색을 해보니 버리는 함수는 없어서 별도로 모듈을 만들어야 한다는데 
사실인지요...... 
사실이라면 어떤식으로 구현해야할지 도움좀 부탁드려봅니다...
  • 답변채택율 100%
  • 추천 0
  • 비추천 0

전체댓글수 9

  • 기술레벨커뮤니티레벨higher 10-12-31 04:13 

    소스보기

  • <?php 
    $a=100.123456; 
    $b=sprintf("%.2f",$a); 
    echo $b; //100.12 
    ?>
  • 기술레벨커뮤니티레벨쥬리엘 10-12-31 09:17 

    소스보기

  • echo floor(100.123456 * 100) / 100; 
    or 
    echo intval(100.123456 * 100) / 100; 
    방법은 많지만 쓰기 나름이죠..
  • 기술레벨커뮤니티레벨가산 10-12-31 09:18 

    소스보기

  • numberformat($int,자리수);
  • 기술레벨커뮤니티레벨쥬리엘 10-12-31 09:20 

    소스보기

  • 오우.. number_format()의 파라미터가 꽤 있었네요.. 
    항상 콤마 찍을때만 써와서.. ㅎㅎ;;
  • 기술레벨커뮤니티레벨망망이 10-12-31 09:53 

    소스보기

  • 우엇 numberformat에 파라메터를 넣을수 있었다늬... 흑.
  • 기술레벨커뮤니티레벨뿔따구 작성자 10-12-31 11:49 

    소스보기

  • 많은 도움들 감사드립니다...새해 복많이 받으세요^^ 
    근데 테스트를 해보니 
    higher 과 가산님 답변 모두 해당자리에서 자동으로 반올림이 되어버리네요 
    100.777 로 테스트 해보면 100.78로 결과값이 나와버리네요... 
    주리엘님 답변같은경우는 정수값 100이 결과로 나와버리구요... 
    방법이 없지는 않을거 같은데 생각보다 까라로운가봐요 ㅠㅠ
  • 기술레벨커뮤니티레벨BiHon 10-12-31 14:50 

    소스보기

  • 쥬리엘님 답변대로 했는데 100이 나오던가요? 
    그리고 어떤 식으로 했기에 까다롭다는 것인지 모르겠네요. 
    아래는 다 같은 결과 내보냅니다. (방법이야 많지만 대충…) 

    echo floor(100.123456*100)/100; // 제일 간단 

    echo (int)(100.123456*100)/100; // 같은 결과 

    echo round(100.123456,2,PHP_ROUND_HALF_DOWN); // PHP 5.3.x 

    echo preg_replace('/(\d+\.\d{2})(\d*)/','\\1',100.123456); 

    echo substr(100.123456,0,strpos(100.123456,'.')+3); 

    echo reset($t=explode('.',100.123456)).'.'.substr($t[1],0,2); 

    echo implode('.',array_slice(($t=sscanf(100.123456,'%d.%2d%d')),0,2));
  • 기술레벨커뮤니티레벨쥬리엘 10-12-31 16:43 

    소스보기

  • 음.. 100이 나올리 없습니다. ㅎㅎ;; 
    어딘가 계산하는 부분을 잘못적으신듯합니다. 괄호하나 빠졌거나...;; ㅎㅎ;; 그럼 에러나겠지만...
  • 기술레벨커뮤니티레벨뿔따구 작성자 10-12-31 21:22 

    소스보기

  • 헐 역쉬 최고의 능력자 비혼님...알려주신 방법 모두 다시한번 테스트 해보겠습니다.... 
    쥬리엘님도 감사드려요..^^


728x90

jQuery 특정 div 새로고침 | Refresh Specific div


Case 1

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt");
    });
});
</script>
</head>
<body>

<div id="div1">
    <h2>Let jQuery AJAX Change This Text</h2>
</div>

<button>Get External Content</button>

</body>
</html>

Case 2 
An easy, but not good way for performance.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load(window.location.href+" #div1 h2");
    });
});
</script>
</head>
<body>

<div id="div1">
    <h2>Let jQuery AJAX Change This Text</h2>
</div>

<button>Get External Content</button>

</body>
</html>

Read more

댓글 없음:


+ Recent posts