免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 17833 | 回复: 1
打印 上一主题 下一主题

请教关于ruby 实现简单http server的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-08-21 18:35 |只看该作者 |倒序浏览
用ruby写个简单的http 服务器
server = TCPServer.new('localhost',  9000)
  loop {
  client = server.accept()
  while((x = client.gets) != "\r\n")
    puts x
  end
  
  puts "正在处理数据..."+ "\r\n"


  $result= "<root><data>123</data></root>"
  headers = ["HTTP/1.1 200 OK",
             "Date: Tue, 14 Dec 2010 10:48:45 GMT",
             "Server: Ruby",
             "Content-Type: text/xml;charset=gb2312",
             "Content-Length: #{$result.bytesize}\r\n\r\n"].join("\r\n")
client.puts headers
client.puts $result
  
  client.close
  puts "Request Handled"


如果用浏览器访问 http://localhost:9000的话是可以正确显示结果xml.
但是如果网页中用jqury的ajax访问的话,IE/FF/Chrome都一样,一直报错,即始终走到error:那个分支,
用firebug看了下,貌似ajax调用只是返回了response的header部分,response本身为空的,有大仙知道原因吗?

$(document).ready(function(){
        $("#btn").click(function(){
                $.ajax({
                    url:"http://localhost:9000",
                    type:"GET",
                    dataType:"xml",
                        async:true,
                    timeout: 2000,
                    error: function(xml, status, err){
                        alert('Error loading XML document'+xml+status+err);
                    },
                    success: function(xml){
                        $(xml).find("data").each(function(i){
                                alert($(this).text());
                           
                        });
                    }
                });
               
        });
       
});

论坛徽章:
0
2 [报告]
发表于 2013-08-21 22:20 |只看该作者
ok, I got the reason. AJAX should only access the URL in the same domain. I put the AJAX code in a local HTML, hence can't access the server.

updated server code as below, and put the AJAX html under "/", the access point it "http://localhost:9000/ajax.html"

require 'webrick'

$mydata="<root><data>test1</data><data>test2</data></root>"
class MyServlet < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request, response)
    response.status = 200
    response.content_type = "text/xml"
    response.body = $mydata
  end
end

server = WEBrick::HTTPServer.new(ort => 9000,ocumentRoot=>Dir::pwd)
server.mount "/data", MyServlet
trap("INT"{ server.shutdown }
server.start
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP