Blazor Server, 从异步JavaScript函数获取返回值

huangapple go评论66阅读模式
英文:

Blazor Server, get return value from Async Javascript Function

问题

I can provide a translation for the code portion you've shared:

在尝试解决这个问题时我苦思冥想,我可以将同步的 JavaScript 值从 JavaScript 传递到 Blazor,但是异步的值却无法传递。

假设我有以下代码:

.razor

private async Task GetJSRemoteIP()
{
    string remoteIP = await JSRunTime.InvokeAsync<string>("getIPadr");
}

.js

function getIPadr() {
    return "works!";
}

然而,如果我将 JavaScript 更改为带有返回值的异步函数,就无法将其传递回 Blazor,如下所示:

.js 

async function getIPadr() {
    const response = await fetch("https://api.ipify.org?format=json");
    const jsonData = await response.json();
    return jsonData;
}
如何才能将异步函数的值传递回 Blazor?

Please note that I've provided the translation of the code while excluding the specific request to translate.

英文:

Racking my brain trying to get this working, I can get synchronous JS values from JS to Blazor, but async doesn't get sent over.

Let's say I have the following code:

.razor

private async Task GetJSRemoteIP()
{
    string remoteIP = await JSRunTime.InvokeAsync&lt;string&gt;(&quot;getIPadr&quot;);
}

.js

function getIPadr() {
return &quot;works!&quot;
}

however, if I change the js to an async function with return, it never gets sent back to blazor, like so:

.js

async function getIPadr() {
const response = await fetch(&quot;https://api.ipify.org?format=json&quot;);
const jsonData = await response.json();
return jsonData;

}

What do I need to do to get the async function value back into blazor with return?

答案1

得分: 1

你的代码看起来没问题。然而,在返回JSON数据时似乎出现了问题。可能是JSON对象没有隐式地转换为字符串类型。

由于响应是JSON,你可以直接访问数据成员并返回它。

return jsonData.ip;

或者,你可以显式将其转换为字符串并发送回服务器。

return JSON.stringify(jsonData);

以上方法需要在服务器端添加一个反序列化机制来从JSON中获取IP。

英文:

Your code looks fine. However, there seems to be a problem when returning the JSON data. Presumably, the JSON object is not implicitly getting typecasted to a string type.

Since the response is a JSON, you can access the data member directly and return it.

return jsonData.ip;

Alternatively, you can explicitly convert it to a string and send it back to the server.

return JSON.stringify(jsonData);

Above will require adding a deserializing mechanism on the server side to get IP from the JSON.

huangapple
  • 本文由 发表于 2023年5月24日 19:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76323263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定