我是网络开发新手,正在尝试正确更新我在发布请求后创建的弹出窗口。我这样做的方式似乎太复杂了。 基本上我有一个 chrome 扩展,它在某个时刻向我的数据库发出 post 请求并返回一个 url。然后我想打开一个弹出窗口,并将我的数据库刚刚在弹出窗口中传递的 URL 包含在内。这看起来很简单,我确信我当前的设计过于复杂: 在 content.js 中,我调用函数 doWork:
function doWork(itemName, itemPrice) {
var items = [{'itemName': itemName, 'price': itemPrice}]
// ajax the JSON to the server
$.post('https:my/url/receiver', JSON.stringify(items),
function(data, status){
chrome.runtime.sendMessage({type:'open_deals_page', url:data.url})
});
}
这是由 background.js 在以下函数中接收的:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'open_deals_page') {
chrome.tabs.create({
url: chrome.extension.getURL('popup.html'),
active: false
}, function(tab) {
chrome.windows.create({
tabId: tab.id,
type: 'panel',
height: 200, width:200,
focused: true,
// incognito, top, left, ...
});
adjust_window(request.url)
});
}
});
在理想的情况下,函数 adjustment_window 会改变 下面的 popup.html 中 id='itemUrl' 的 html 元素:
<!DOCTYPE html><html><head><title>Dialog test</title></head><body>
</title>There is a better deal elsewhere on the web @</title>
<a href="giggle.com" id='itemUrl'>the url you requested</a>
</html>
不用说,我不确定如何设置 adjustment_window 函数或者是否在正确的位置调用它。我尝试了各种 jquery 选择器并不断获得空值。我也对如何确保访问刚刚打开的特定弹出窗口感到困惑。谢谢!
最佳答案
是否需要从content.js
发出网络请求?这似乎可能在后台发生。如果问题是对 jQuery 的访问(对于 $.post
),那么我建议检查 native fetch
函数。对于你来说,它看起来像
fetch(
'https://your/url/receiver',
{
method: 'POST',
body: JSON.stringify(items)
}
).then(res => res.json()).then(data => data.url)
上面使用了“箭头函数表达式”,但如果这些使理解变得困难,下面是等效的!
fetch(
'https://your/url/receiver',
{
method: 'POST',
body: JSON.stringify(items)
}
).then(function(res) { return res.json() }).then(function(data) { return data.url })
关于javascript - 使用发布请求的结果更新网页的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61132995/