2014-06-23 4 views
0

bottlepy 서버에서 json 데이터를 웹 페이지로 가져 오려고합니다. 우선 기본 버전을 구현하려고 했으므로 문자열 만 사용해 보았습니다. 그러나 아무 것도 일어나지 않는 것 같습니다. (JS 포함)AJAX를 사용하여 Bottlepy 서버에서 데이터 가져 오기

HTML - -

<!DOCTYPE> 
<html> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 

<body> 
<script> 
function print() 
{ 
    $(document).ready(function(){ 
     $.get('http://localhost:8080/check', function(result){ 
      alert('success'); 
      $('#main').html(result); 
     }); 
    }); 
} 

print(); 
</script></body> 
</html> 

파이썬 코드 -

from bottle import Bottle, route, get,request, response, run, template 

app = Bottle() 

@app.hook('after_request') 
def enable_cors(): 
    response.headers['Access-Control-Allow-Origin'] = '*' 

# a simple json test main page 
str = "Hello" 
@route('/')     #irrelevant to this question. Used this to check server... 
def test(): 
    return template('file', str) 

@app.get('/check') 
def showAll(): 
    return str 

run(host='localhost', port=8080) 

내가 서버의 데이터에 액세스하려면 어떻게해야합니까 여기에 코드? 참고 : HTML은 별도의 파일이므로 HTML의 위치에 관계없이 코드가 작동하도록하고 싶습니다.

또한 이것이 불가능할 경우 템플릿을 사용하여 어떻게 할 수 있습니까?

+0

당신이 브라우저에서'/ check'에 액세스 할 수 있습니까? 아마도'run (app = app, host = ...)'를 사용해야 할 것입니다. 'run (...) '을 완전히 제거하고 대신에'python -m bottle --reload --debug : app'을 사용하여 개발하십시오. – user41047

+0

app.get()을 route()로 변경하면/check가 브라우저에서 완벽하게로드됩니다. – SMP288

답변

0

귀하의 문제는 병 응용 프로그램과의 혼란에 기인합니다.

병은 @route(more on this)을 사용할 때마다 기본 앱을 만들고 이후 기본 전화를 암시 적으로 재사용합니다. 이 기본 앱 동작은 많은 기능 (예 : hookrun)에 있습니다.

점은 다음과 같습니다

app = Bottle() # creates an explicit app 

@route('/') # adds the route to the default app 

@app.hook('after-request') # adds the hook to the explicit app 

run(...) # runs the default app, the hook is not used 

두 가지 옵션이 문제를 해결하기 위해 :

  • 가 명시 적으로 응용 프로그램에 대한 언급을 제거하십시오;
  • 항상 응용 프로그램에게 I 앱이 명시 적으로 무슨 일이 있었는지 쉽게 하위 응용 프로그램을 만드는 데 훨씬 더 명확 일반적으로 만들어 사용하여 발견 명시 적으로

를 사용합니다.

새로운 코드 :

import bottle 
from bottle import response, template, run 

app = bottle.Bottle() 

@app.hook('after_request') 
def enable_cors(): 
    response.headers['Access-Control-Allow-Origin'] = '*' 

# a simple json test main page 
str = "Hello" 
@app.route('/')     #irrelevant to this question. Used this to check server... 
def test(): 
    return template('file', str) 

@app.get('/check') 
def showAll(): 
    return str 

run(app=app, host='localhost', port=8080) 
+0

감사합니다! 지금 일하고있어! – SMP288

관련 문제