pub fn fetch_shortcode_js(
url: &str,
method: Option<&str>,
json_body: Option<&str>,
alt: Option<&str>,
) -> StringExpand description
Generates a JavaScript snippet that asynchronously fetches data from a URL using either the GET or POST HTTP method and injects the response into the DOM. The function also provides fallback content for crawlers/robots that do not support JavaScript. If the response has JavaScript code like , it will be executable.
§Parameters
url: A string slice containing the URL to which the HTTP request will be made.method: An optional HTTP method, eitherGETorPOST. Defaults toGETifNoneis provided.json_body: An optional JSON string for the request body when using thePOSTmethod. Defaults to an empty JSON object ({}) ifNoneis provided. Ignored if the method isGET.alt: An optional alternative content to display in a<noscript>block for crawlers/robots without JavaScript. This is only used if the method isGET. Defaults toNone.
§Returns
A String containing the generated JavaScript code that can be inserted into an HTML page. The script:
- Sends an asynchronous
fetchrequest to the specified URL. - If the response is successful, it injects the response content into the DOM.
- If the request fails, it logs an error message to the browser’s console.
- If an invalid HTTP method is passed (anything other than
GETorPOST), an HTML<output>element with an error message is returned instead of the JavaScript code.
If the GET method is used and alt is provided, the function also includes a <noscript> fallback
to display a link in case JavaScript is disabled or not supported.
§Example
use tera_shortcodes::fetch_shortcode_js;
let js_code = fetch_shortcode_js(
"https://example.com/data",
Some("POST"),
Some("{\"key\": \"value\"}"),
Some("No JavaScript fallback")
);
println!("{}", js_code);This will generate JavaScript code to make a POST request to https://example.com/data with the
provided JSON body, and include a fallback for users without JavaScript.
§Error Handling
- If an unsupported HTTP method is provided (anything other than
GETorPOST), the function will return an HTML<output>element with an error message specifying the invalid method.