【问题标题】:Get and javascript? like php's if $_GET[foo]获取和javascript?像 php 的 if $_GET[foo]
【发布时间】:2016-01-03 01:16:17
【问题描述】:

我正在编写一个javascript http web服务器节点,对于一个CDN项目,我习惯了PHP的

if ($_GET = "hello"); echo "Yey!"

但不知道该怎么做,我是 javascript 新手。

【问题讨论】:

  • 这是您之前问题的重复:stackoverflow.com/questions/34559227/…?
  • 前面的问题已经回答了,但是答案跑题了,给我的代码是针对 node.JS 网络服务器的。
  • @alextix,检查我的答案

标签: javascript node.js get


【解决方案1】:

NodeJS

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

没有 NodeJS:
使用 URI.js 获取查询字符串。 https://medialize.github.io/URI.js/

var uri = URI("urn:uuid:c5542ab6-3d96-403e-8e6b-b8bb52f48d9a?hello=world");
uri.protocol() == "urn";
uri.path() == "uuid:c5542ab6-3d96-403e-8e6b-b8bb52f48d9a";
uri.query() == "hello=world";

【讨论】:

    【解决方案2】:

    你可以试试这个功能:

    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return xmlHttp.responseText;
    }
    

    但是,不鼓励同步请求,因此您可能希望改用它:

    function httpGetAsync(theUrl, callback)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() { 
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                callback(xmlHttp.responseText);
        }
        xmlHttp.open("GET", theUrl, true); // true for asynchronous 
        xmlHttp.send(null);
    }
    

    注意事项:从 Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,主线程上的同步请求已被弃用,因为这会对用户体验造成负面影响。

    【讨论】:

    • 如何进行简单的变量比较?喜欢 ===
    • 在 javascript 中我认为是这样的 == 或 ===
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2017-02-13
    • 2011-10-02
    相关资源
    最近更新 更多