Return Ajax 多项
Return multiple items for Ajax
我有这个 python 代码可以在 ebay 上搜索 return 搜索字符串的结果。代码正确执行并且 returns 结果如我所愿,但仅当我使用 print() 函数时。我正在使用 json 将结果解析到烧瓶页面,使用 print() 仅打印到控制台所以我使用 return 但它没有给出所有结果,它 returns只有一项。
如何让代码 return 显示所有结果并显示在我的 flask 页面上?
我是 python 的新手,这是我的第一个项目。我之前问过这个问题并将代码升级到现在的状态,我一直在互联网上搜索解决方案,但我还没有找到任何解决方案。请有人帮我提供一个代码,该代码将 return 从搜索中获得的所有结果。
后端
@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
if request.method == 'POST':
#Get json format of the text sent by Ajax
search = request.json['search']
try:
#ebaysdk code starts here
api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
response = api.execute('findItemsAdvanced', api_request)
soup = BeautifulSoup(response.content, 'lxml')
totalentries = int(soup.find('totalentries').text)
items = soup.find_all('item')
# This will be returned
itemsFound = {}
# This index will be incremented
# each time an item is added
index = 0
for item in items:
cat = item.categoryname.string.lower()
title = item.title.string.lower().strip()
price = int(round(float(item.currentprice.string)))
url = item.viewitemurl.string.lower()
seller = item.sellerusername.text.lower()
listingtype = item.listingtype.string.lower()
condition = item.conditiondisplayname.string.lower()
print ('____________________________________________________________')
#return json format of the result for Ajax processing
#return jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)
# Adding the item found in the collection
# index is the key and the item json is the value
itemsFound[index] = jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)
# Increment the index for the next items key
index+=1
for key in itemsFound:
return itemsFound[key]
except ConnectionError as e:
return jsonify(e)
Ajax
$(document).ready(function() {
$(".button").click(function() {
var search = $(".search").val().trim();
if (search) {
$.ajax({
type: 'POST',
url: "{{url_for('ebay_page_post')}}",
data: JSON.stringify({ 'search': search }),
contentType: 'application/json;charset=UTF-8',
dataType: "json",
success:function(data) {
if (data.indexOf("|") >= 0) {
var newData = data.split("|");
var category = newData[0];
var title = newData[1];
var price = newData[2]
var url = newData[3];
var seller = newData[4];
var listingType = newData[5];
var condition = newData[6];
$("#returned").html("");
$("#returned").append(returned(category, title, price, url, seller, listingType, condition));
} else {
$("#returned").html("<label>"+data+"</label>");
}
}
});
}
});
});
function returned(category, title, price, url, seller, listingType, condition) {
return '<div class="col-lg-6"> ' +
'<div class="box">'+
'<div class="icon"><i class="ion-ios-heart-outline"></i></div>' +
'<h4 class="title">'+title+'</h4>' +
'<h5>'+category+'</h5>' +
'<small><a href="'+url+'" target="_blank">Go to site</a></small>'+
'<div class="description">' +
'Price: <strong>'+price+'</strong>' +
'<p>Seller: <strong>'+seller+'</strong></p>' +
'<p>'+listingType+'</p>' +
'<p>Condition: '+condition+'</p>' +
'</div>' +
'</div>' +
'</div>'
}
您的 python 代码只是 return 您的 itemsFound
列表中的第一项,因为这是您要它执行的操作:
for key in itemsFound:
return itemsFound[key]
... 为什么不 return 整个列表?像这样
return itemsFound
我通过修改我的代码解决了这个问题:
#!/usr/bin/env python
import os
import sys
import pprint
import locale
import time
import datetime
import ebaysdk
from ebaysdk.finding import Connection as finding
from ebaysdk.exception import ConnectionError
from bs4 import BeautifulSoup
from flask import Flask
from flask import request, render_template, jsonify
HTML_OUTPUT = """
<div class=\"col-lg-6\">
<div class=\"box wow fadeInLeft\">
<div class=\"icon\"><img src=\"%s\" alt=\"Item Image\"></div>
<h4 class=\"title\">%s</h4>
<ul>
<li>Price: $ %s</li>
<li>Seller: %s</li>
<li>Condition: %s</li>
<li>Listing Type: %s</li>
</ul>
<small><a href="%s" target="_blank">Go to site</a></small>
</div>
</div>"""
# Instantiate our Flask class.
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Decide which URL will trigger everything...
@app.route('/')
def ebay_serve_page():
empty_folder()
return render_template("index.html")
def empty_folder():
folder = 'static'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
# Grab search string entered by user...
@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
if request.method == 'POST':
#Get json format of the text sent by Ajax
search = request.json['search']
try:
#ebaysdk code starts here
api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
response = api.execute('findItemsAdvanced', api_request)
soup = BeautifulSoup(response.content, 'lxml')
items = soup.find_all('item')
# This will be returned
items_found = []
for item in items:
pic = item.PictureURL
title = item.title.string.strip()
price = float(item.currentprice.string)
url = item.viewitemurl.string.lower()
seller = item.sellerusername.text
listingtype = item.listingtype.string
condition = item.conditiondisplayname.string
print ('____________________________________________________________')
# Adding the item found in the collection
items_found.append(HTML_OUTPUT % (pic,
title,
price,
seller,
condition,
listingtype,
url))
f = open("static/"+search+".html", 'w+')
for item in items_found:
f.write("%s" % item)
f.close()
return "1"
except ConnectionError as e:
return jsonify(e)
if __name__ == '__main__':
app.run(debug = True)
然后我将 ajax 调用修改为:
$(document).ready(function() {
$(".button").click(function() {
var search = $(".search").val().trim();
var file = search + ".html";
if (search) {
$.ajax({
type: 'POST',
url: "{{url_for('ebay_page_post')}}",
data: JSON.stringify({ 'search': search }),
contentType: 'application/json;charset=UTF-8',
dataType: "json",
success:function(data) {
if (data == "1") {
$.ajax({
url:"/static/"+file,
dataType:'html',
success: function(items){
$('#returned').html(items);
}
});
} else {
$("#returned").html(data);
}
}
});
}
});
});
感谢每一位帮助过的人。
我有这个 python 代码可以在 ebay 上搜索 return 搜索字符串的结果。代码正确执行并且 returns 结果如我所愿,但仅当我使用 print() 函数时。我正在使用 json 将结果解析到烧瓶页面,使用 print() 仅打印到控制台所以我使用 return 但它没有给出所有结果,它 returns只有一项。
如何让代码 return 显示所有结果并显示在我的 flask 页面上?
我是 python 的新手,这是我的第一个项目。我之前问过这个问题并将代码升级到现在的状态,我一直在互联网上搜索解决方案,但我还没有找到任何解决方案。请有人帮我提供一个代码,该代码将 return 从搜索中获得的所有结果。
后端
@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
if request.method == 'POST':
#Get json format of the text sent by Ajax
search = request.json['search']
try:
#ebaysdk code starts here
api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
response = api.execute('findItemsAdvanced', api_request)
soup = BeautifulSoup(response.content, 'lxml')
totalentries = int(soup.find('totalentries').text)
items = soup.find_all('item')
# This will be returned
itemsFound = {}
# This index will be incremented
# each time an item is added
index = 0
for item in items:
cat = item.categoryname.string.lower()
title = item.title.string.lower().strip()
price = int(round(float(item.currentprice.string)))
url = item.viewitemurl.string.lower()
seller = item.sellerusername.text.lower()
listingtype = item.listingtype.string.lower()
condition = item.conditiondisplayname.string.lower()
print ('____________________________________________________________')
#return json format of the result for Ajax processing
#return jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)
# Adding the item found in the collection
# index is the key and the item json is the value
itemsFound[index] = jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)
# Increment the index for the next items key
index+=1
for key in itemsFound:
return itemsFound[key]
except ConnectionError as e:
return jsonify(e)
Ajax
$(document).ready(function() {
$(".button").click(function() {
var search = $(".search").val().trim();
if (search) {
$.ajax({
type: 'POST',
url: "{{url_for('ebay_page_post')}}",
data: JSON.stringify({ 'search': search }),
contentType: 'application/json;charset=UTF-8',
dataType: "json",
success:function(data) {
if (data.indexOf("|") >= 0) {
var newData = data.split("|");
var category = newData[0];
var title = newData[1];
var price = newData[2]
var url = newData[3];
var seller = newData[4];
var listingType = newData[5];
var condition = newData[6];
$("#returned").html("");
$("#returned").append(returned(category, title, price, url, seller, listingType, condition));
} else {
$("#returned").html("<label>"+data+"</label>");
}
}
});
}
});
});
function returned(category, title, price, url, seller, listingType, condition) {
return '<div class="col-lg-6"> ' +
'<div class="box">'+
'<div class="icon"><i class="ion-ios-heart-outline"></i></div>' +
'<h4 class="title">'+title+'</h4>' +
'<h5>'+category+'</h5>' +
'<small><a href="'+url+'" target="_blank">Go to site</a></small>'+
'<div class="description">' +
'Price: <strong>'+price+'</strong>' +
'<p>Seller: <strong>'+seller+'</strong></p>' +
'<p>'+listingType+'</p>' +
'<p>Condition: '+condition+'</p>' +
'</div>' +
'</div>' +
'</div>'
}
您的 python 代码只是 return 您的 itemsFound
列表中的第一项,因为这是您要它执行的操作:
for key in itemsFound:
return itemsFound[key]
... 为什么不 return 整个列表?像这样
return itemsFound
我通过修改我的代码解决了这个问题:
#!/usr/bin/env python
import os
import sys
import pprint
import locale
import time
import datetime
import ebaysdk
from ebaysdk.finding import Connection as finding
from ebaysdk.exception import ConnectionError
from bs4 import BeautifulSoup
from flask import Flask
from flask import request, render_template, jsonify
HTML_OUTPUT = """
<div class=\"col-lg-6\">
<div class=\"box wow fadeInLeft\">
<div class=\"icon\"><img src=\"%s\" alt=\"Item Image\"></div>
<h4 class=\"title\">%s</h4>
<ul>
<li>Price: $ %s</li>
<li>Seller: %s</li>
<li>Condition: %s</li>
<li>Listing Type: %s</li>
</ul>
<small><a href="%s" target="_blank">Go to site</a></small>
</div>
</div>"""
# Instantiate our Flask class.
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Decide which URL will trigger everything...
@app.route('/')
def ebay_serve_page():
empty_folder()
return render_template("index.html")
def empty_folder():
folder = 'static'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
# Grab search string entered by user...
@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
if request.method == 'POST':
#Get json format of the text sent by Ajax
search = request.json['search']
try:
#ebaysdk code starts here
api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
response = api.execute('findItemsAdvanced', api_request)
soup = BeautifulSoup(response.content, 'lxml')
items = soup.find_all('item')
# This will be returned
items_found = []
for item in items:
pic = item.PictureURL
title = item.title.string.strip()
price = float(item.currentprice.string)
url = item.viewitemurl.string.lower()
seller = item.sellerusername.text
listingtype = item.listingtype.string
condition = item.conditiondisplayname.string
print ('____________________________________________________________')
# Adding the item found in the collection
items_found.append(HTML_OUTPUT % (pic,
title,
price,
seller,
condition,
listingtype,
url))
f = open("static/"+search+".html", 'w+')
for item in items_found:
f.write("%s" % item)
f.close()
return "1"
except ConnectionError as e:
return jsonify(e)
if __name__ == '__main__':
app.run(debug = True)
然后我将 ajax 调用修改为:
$(document).ready(function() {
$(".button").click(function() {
var search = $(".search").val().trim();
var file = search + ".html";
if (search) {
$.ajax({
type: 'POST',
url: "{{url_for('ebay_page_post')}}",
data: JSON.stringify({ 'search': search }),
contentType: 'application/json;charset=UTF-8',
dataType: "json",
success:function(data) {
if (data == "1") {
$.ajax({
url:"/static/"+file,
dataType:'html',
success: function(items){
$('#returned').html(items);
}
});
} else {
$("#returned").html(data);
}
}
});
}
});
});
感谢每一位帮助过的人。