### NativeUI Example - Show Menu Source: https://www.dcloud.io/docs/api/zh_cn/nativeui Example demonstrating how to display a native UI menu and handle item clicks. ```APIDOC ## NativeUI Example - Show Menu ### Description This example shows how to use `plus.nativeUI.showMenu` to display a custom menu and handle the `onclicked` callback function when a menu item is selected. ### Method `plus.nativeUI.showMenu( options, items, callback )` ### Endpoint None (This is a client-side JavaScript API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript function showMenu(){ plus.nativeUI.showMenu({ title:"比价", badge:true }, [ {title:"淘宝网"} ,{title:"京东"} ,{title:"唯品会",checked:true} ], onclicked); } // Clicked menu item callback function function onclicked(e){ var index = e.index; var item = e.target; console.log("用户点击了第"+index+"项: "+item.title); } ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Example: Creating a Native View Object Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Demonstrates how to create and draw content onto a NativeObj View object. ```APIDOC ## Example: Creating a View Object ### Description This example demonstrates the creation of a `plus.nativeObj.View` object and drawing various elements onto it, including an image, a rectangle, and text. ### Method `plus.nativeObj.View` constructor and `draw` method. ### Endpoint N/A (Client-side JavaScript API) ### Request Body Example ```javascript // Create a native View control view = new plus.nativeObj.View('test', { top: '0px', left: '0px', height: '44px', width: '100%' }); // Draw elements onto the view view.draw([ { tag: 'img', id: 'img', src: 'nbg.png', position: { top: '0px', left: '0px', width: '100%', height: '100%' } }, { tag: 'rect', id: 'rect', rectStyles: { color: '#FF0000' }, position: { top: '0px', left: '0px', width: '100%', height: '1px' } }, { tag: 'font', id: 'font', text: '原生控件', textStyles: { size: '18px' } } ]); // Show the view view.show(); ``` ### Response N/A (This is a client-side operation and does not involve a server response in the traditional sense. The view will be displayed on the device.) ``` -------------------------------- ### Full Example: NativeObj View Operations (HTML/JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj A complete HTML and JavaScript example demonstrating the creation, styling, event handling, and visibility control of a DCloud NativeObj View. It includes buttons to trigger these actions. ```html NativeObj Example





``` -------------------------------- ### HTML Example: Get Phone Address Book Source: https://www.dcloud.io/docs/api/zh_cn/contacts This HTML and JavaScript example demonstrates how to get the phone's address book using `plus.contacts.getAddressBook` after the 'plusready' event is fired. It includes success and error alert messages. ```html Contacts Example ``` -------------------------------- ### Load and Animate Bitmaps with NativeObj View Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj This example demonstrates how to load two bitmaps ('bmp1.png', 'bmp2.png') into native objects and then use them to create a native animation using plus.nativeObj.View.startAnimation. It also shows how to clear the bitmaps from memory. This functionality is useful for creating custom native UI transitions and effects within the H5+ environment. ```html NativeObj Example

``` -------------------------------- ### ViewStyles Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Defines the styles for a View control, including position, size, and appearance. ```APIDOC ## ViewStyles ### Description Includes information such as position and size. Position information is calculated relative to the parent container. ### Properties - **backgroundColor** (String) - Background color of the area. Color format is "#RRGGBB", e.g., "#FF0000" for red. Defaults to transparent. - **bottom** (String) - Offset of the View control upwards from the bottom. Can be a pixel value (e.g., "100px") or a percentage (e.g., "10%") relative to the parent container's height (or screen height if no parent). Ignored if `top` and `height` are set. If `height` is not set, `top` and `bottom` determine the View control's height. - **dock** (String) - Docking method for the View control. Only effective when the View control is added to a Webview window object and the `position` property is set to "dock". In this case, the View control squeezes the Webview window size. Possible values: "top", "bottom", "right", "left". Defaults to "top". - **height** (String) - Height of the area. Can be a pixel value (e.g., "100px"), a percentage (e.g., "10%") relative to the parent container's height (or screen height if no parent), or "wrap_content" for content-based height. Defaults to "100%." - **left** (String) - Horizontal offset of the top-left corner of the area. Can be a pixel value (e.g., "100px"), a percentage (e.g., "10%") relative to the parent container's width, or "auto" for automatic calculation (centering horizontally relative to the parent). Defaults to "0px". - **opacity** (Number) - Opacity of the View control. Value ranges from 0 (fully transparent) to 1 (fully opaque). Defaults to 1. - **position** (String) - Position property. Set to "dock" to enable docking. - **statusbar** (ViewStatusbarStyles) - Styles for the system status bar area. ``` -------------------------------- ### Initialize Marker Drag Event Source: https://www.dcloud.io/docs/api/zh_cn/maps An example of setting up a drag event listener for a map marker. When the marker is dragged, this function will be called, providing information about the marker's new position. ```javascript markObj.onDrag = function ( target ) { alert( "Drag:" + JSON.stringify(target.getPoint()) ); } ``` -------------------------------- ### HTML Example: Create and Save Contact Source: https://www.dcloud.io/docs/api/zh_cn/contacts This HTML and JavaScript example shows how to create a new contact with a given name and phone number, and then save it to the address book. It's triggered after obtaining the address book object. ```html Contacts Example ``` -------------------------------- ### ViewStatusbarStyles Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Defines the styles for the system status bar area of a View control. ```APIDOC # ViewStatusbarStyles ### Description A JSON object defining the system status bar area styles for a View control. This is only effective when the application is set to an immersive status bar style; it is ignored in non-immersive status bar styles. ### Properties - **background** (String) - Background color of the system status bar area. Color format is "#RRGGBB", e.g., "#FF0000" for red. Defaults to the value configured in the `plus.statusbar.background` property in `manifest.json`. ``` -------------------------------- ### Configure Circle Properties Source: https://www.dcloud.io/docs/api/zh_cn/maps Provides examples of how to set various visual properties for a map circle, including its center, radius, stroke color, stroke opacity, fill color, and line width. These methods allow for dynamic customization of the circle's appearance. ```javascript // Set new circle center circleObj.setCenter( new plus.maps.Point(116.0, 39.0) ); // Set new circle radius circleObj.setRadius( 1000 ); // Set circle border color to red circleObj.setStorkeColor( "#ff0000" ); // Set circle border opacity circleObj.setStrokeOpacity( 0.5 ); // Set circle fill color circleObj.setFillColor( "#0000ff" ); // Set circle fill opacity circleObj.setFillOpacity( 0.3 ); // Set circle border line width circleObj.setLineWidth( 3 ); ``` -------------------------------- ### Get NativeViewById in JavaScript Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj This example demonstrates how to use the static method plus.nativeObj.View.getViewById(id) to retrieve a native View object by its unique identifier. If multiple views with the same ID exist, it returns the first one. If no view is found, it returns null. This is crucial for interacting with existing native UI elements. ```javascript View plus.nativeObj.View.getViewById(id); ``` ```html NativeObj Example


``` -------------------------------- ### Create Native View with H5+ NativeObj (JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Demonstrates how to create a native view using the plus.nativeObj.View API and draw a hollow rounded rectangle on it. This requires the H5+ environment to be ready. ```javascript NativeObj Example
``` -------------------------------- ### Show NativeUI Menu Example (HTML/JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeui An HTML page demonstrating how to display a native UI menu using JavaScript. It includes event handling for the menu button and the item click callback. ```html NativeUI Example 自定义导航栏菜单

``` -------------------------------- ### Create and Configure a Map Bubble Source: https://www.dcloud.io/docs/api/zh_cn/maps Demonstrates how to create a map bubble, associate it with a marker, and set its icon and label. This involves instantiating a Bubble object and then using marker methods to link them. ```javascript var marker = new plus.maps.Marker(new plus.maps.Point(116.347496, 39.970191)); marker.setIcon("/logo.png"); marker.setLabel("HBuilder"); var bubble = new plus.maps.Bubble("打造最好的HTML5移动开发工具"); marker.setBubble(bubble); map.addOverlay(marker); ``` -------------------------------- ### Animate View Content with NativeObj View Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj This example demonstrates how to apply animations to the content of a native View object using the animate method. It accepts an options object for animation parameters and an optional callback function that is executed once the animation completes. Note that after animation, the view's content might change, and the view itself might need to be cleared if it's no longer needed. ```javascript void view.animate(options, callback); ``` -------------------------------- ### Add and Remove Map Overlay (Marker) (JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/maps This example shows how to add a marker with an icon, label, and bubble to a map, and subsequently remove it. It utilizes the plus.maps.Marker, plus.maps.Point, plus.maps.Bubble, and map.addOverlay/removeOverlay methods. This functionality is crucial for visualizing specific locations on the map. ```javascript var em=null,map=null; // H5 plus事件处理 function plusReady(){ // 确保DOM解析完成 if(!em||!window.plus||map){return}; map = new plus.maps.Map("map"); map.centerAndZoom( new plus.maps.Point(116.3977,39.906016), 12 ); } if(window.plus){ plusReady(); }else{ document.addEventListener("plusready",plusReady,false); } // DOMContentloaded事件处理 document.addEventListener("DOMContentLoaded",function(){ em=document.getElementById("map"); plusReady(); },false); // 添加标点 var marker=null; function addMarker(){ if(marker){return;} marker=new plus.maps.Marker(new plus.maps.Point(116.347496,39.970191)); marker.setIcon("/logo.png"); marker.setLabel("HBuilder"); var bubble = new plus.maps.Bubble("打造最好的HTML5移动开发工具"); marker.setBubble(bubble); map.addOverlay(marker); } // 删除标点 function removeMarker(){ map.removeOverlay(marker); delete marker; marker=null; } ``` -------------------------------- ### Add Event Listener to Native View in JavaScript Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj This example shows how to attach an event listener to a native View object using the addEventListener method. It specifically demonstrates listening for 'click' events and provides a callback function that logs touch event details such as coordinates and the target view. This is essential for making native UI elements interactive. ```javascript void view.addEventListener(event, listener, capture); ``` ```html NativeObj Example

``` -------------------------------- ### Create a Map Bubble Object Source: https://www.dcloud.io/docs/api/zh_cn/maps Demonstrates the basic instantiation of a map bubble object with a given label. This is a foundational step before associating the bubble with a map marker. ```javascript var bubObj = new plus.maps.Bubble( label ); ``` -------------------------------- ### setStyle Method Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Dynamically updates the styles of a View control, allowing modification of properties like position and size. ```APIDOC ## setStyle ### Description Dynamically updates the styles of a View control. ### Method `void view.setStyle(styles);` ### Parameters #### Request Body - **styles** (ViewStyles) - Optional - The styles to apply to the View control. ### Request Example ```json { "top": "0px", "left": "0px", "height": "50%", "width": "100%" } ``` ### Response #### Success Response (200) No specific response body, returns void. ### Response Example ```json null ``` ``` -------------------------------- ### Start Video Capture API Source: https://www.dcloud.io/docs/api/zh_cn/camera Initiates video recording using the device's camera. Similar to image capture, it accepts success and error callbacks, and optional parameters for video settings. ```APIDOC ## startVideoCapture ### Description Initiates video recording using the device's camera. The camera resource is exclusive. Upon successful recording, the video file path will be returned via the `successCB`. The `option` parameter allows for setting various camera properties. ### Method JavaScript function call ### Endpoint Not applicable (client-side API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **successCB** (CameraSuccessCallback) - Required - Callback function executed upon successful video capture. - **errorCB** (CameraErrorCallback) - Optional - Callback function executed upon failure of the video capture operation. - **option** (CameraOption) - Required - An object containing parameters for the video capture operation. ### Request Example ```javascript cmr.startVideoCapture( successCB, errorCB, option ); ``` ### Response #### Success Response void: No direct return value. The success callback receives the video file path. #### Response Example ```javascript // Inside successCB: function( path ) { // path is the captured video file path } ``` ### Platform Support - Android - 2.2+ (Supported) - iOS - 4.3+ (Supported) ``` -------------------------------- ### Load Bubble Content from Image Data URL Source: https://www.dcloud.io/docs/api/zh_cn/maps Provides an example of setting the bubble's content using image data in a Data URL format. This is useful for dynamically generated images or images encoded as Base64 strings. ```javascript void bubObj.loadImageDataURL( data ); ``` -------------------------------- ### NativeObj View Events Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Defines the events that can be triggered by a NativeObj View control. ```APIDOC ## ViewEvents ### Description Events for the View control. ### Constants - **"doubleclick"** (String) - Double-click event. Triggered when the screen is double-clicked. Note: This event will not be triggered if the View control is set to not intercept touch events (view.interceptTouchEvent(false)). - **"click"** (String) - Click event. Triggered when the finger clicks the screen. Note: This event will not be triggered if the View control is set to not intercept touch events (view.interceptTouchEvent(false)). - **"touchstart"** (String) - Touch start event. Triggered when the finger touches the screen. Note: This event will not be triggered if the View control is set to not intercept touch events (view.interceptTouchEvent(false)). - **"touchmove"** (String) - Touch move event. Continuously triggered when the finger slides on the screen. Note: This event will not be triggered if the View control is set to not intercept touch events (view.interceptTouchEvent(false)). - **"touchend"** (String) - Touch end event. Triggered when the finger leaves the screen. Note: This event will not be triggered if the View control is set to not intercept touch events (view.interceptTouchEvent(false)). ``` -------------------------------- ### Import and Instantiate Objective-C Class in JavaScript Source: https://www.dcloud.io/docs/api/zh_cn/ios Shows how to import an Objective-C class using `plus.ios.importClass` and then create an instance of that class using the `new` keyword. This example demonstrates calling native iOS text-to-speech functionality. ```javascript document.addEventListener("plusready", function() { // Extension API loaded, can now call extension APIs // Call iOS text-to-speech var AVSpeechSynthesizer = plus.ios.importClass("AVSpeechSynthesizer"); var sppech = new AVSpeechSynthesizer(); // Instantiate AVSpeechSynthesizer class object // ... }, false); ``` -------------------------------- ### Start Video Capture with Camera API Source: https://www.dcloud.io/docs/api/zh_cn/camera Initiates video recording using the device's camera. It takes success and error callbacks, along with an options object for parameters like resolution and format. The camera resource is exclusive. ```javascript document.addEventListener( "plusready", onPlusReady, false ); function onPlusReady() { console.log("plusready"); } function videoCapture(){ var cmr = plus.camera.getCamera(); var res = cmr.supportedVideoResolutions[0]; var fmt = cmr.supportedVideoFormats[0]; console.log("Resolution: "+res+", Format: "+fmt); cmr.startVideoCapture( function( path ){ alert( "Capture video success: " + path ); }, function( error ) { alert( "Capture video failed: " + error.message ); }, {resolution:res,format:fmt} ); } ``` -------------------------------- ### hide Method Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Hides the View control from the screen. If the View control is not already visible, this operation has no effect. ```APIDOC ## hide ### Description Hides the View control from the screen. If the View control is not displayed, this operation does nothing. ### Method `void view.hide();` ### Parameters None. ### Request Example ```json null ``` ### Response #### Success Response (200) No specific response body, returns void. ### Response Example ```json null ``` ``` -------------------------------- ### Map Reset and Resize API Source: https://www.dcloud.io/docs/api/zh_cn/maps API endpoints for resetting the map to its initial state and resizing the map control. ```APIDOC ## POST /maps/reset ### Description Resets the map to its initial state, restoring the default center point and zoom level. ### Method POST ### Endpoint /maps/reset ### Parameters None ### Request Example ``` POST /maps/reset ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the map has been reset. #### Response Example ```json { "message": "Map reset successfully." } ``` ``` ```APIDOC ## PUT /maps/resize ### Description Resizes the map control to match the dimensions of its container element. This should be called after the map's container has been resized. ### Method PUT ### Endpoint /maps/resize ### Parameters None ### Request Example ``` PUT /maps/resize ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the map has been resized. #### Response Example ```json { "message": "Map resized successfully." } ``` ``` -------------------------------- ### void view.addEventListener(event, listener, capture) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Adds an event listener to a View control. The listener function is executed when the specified event occurs. Multiple listeners can be added for the same event. ```APIDOC ## void view.addEventListener(event, listener, capture) ### Description Adds an event listener to a View control. The listener function is executed when the specified event occurs. Multiple listeners can be added for the same event. The `capture` parameter is currently ineffective. ### Method `POST` (instance method) ### Endpoint `view.addEventListener` ### Parameters #### Path Parameters - **event** (ViewEvents) - Required - The type of event to listen for (e.g., 'click'). - **listener** (TouchEventCallback) - Required - The callback function to execute when the event occurs. This function receives an event object with details like coordinates. - **capture** (Boolean) - Optional - Specifies the event capture phase; currently has no effect. ### Request Example ```javascript view.addEventListener('click', function(e) { console.log('View clicked at:', e.clientX, e.clientY); }, false); ``` ### Response #### Success Response (200) - **void** - This method does not return a value. ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Overlay Management API Source: https://www.dcloud.io/docs/api/zh_cn/maps API endpoints for managing overlay objects on the map, including adding and removing them. ```APIDOC ## POST /maps/overlays ### Description Adds an overlay object to the map. This can be used for markers, bubbles, or other graphical elements. ### Method POST ### Endpoint /maps/overlays ### Parameters #### Request Body - **overlay** (object) - Required - The overlay object to add to the map. This object should conform to the `maps.Overlay` type definition. - **type** (string) - The type of overlay (e.g., 'Marker', 'Bubble'). - **point** (object) - The geographic coordinates for the overlay. - **longitude** (number) - The longitude. - **latitude** (number) - The latitude. - **label** (string) - Optional - A text label for the overlay. - **bubble** (object) - Optional - A bubble associated with the overlay. - **content** (string) - The content of the bubble. ### Request Example ```json { "overlay": { "type": "Marker", "point": { "longitude": 116.347496, "latitude": 39.970191 }, "label": "HBuilder", "bubble": { "content": "打造最好的HTML5移动开发工具" } } } ``` ### Response #### Success Response (200) - **overlayId** (string) - A unique identifier for the added overlay. #### Response Example ```json { "overlayId": "overlay_12345" } ``` ``` ```APIDOC ## DELETE /maps/overlays/{overlayId} ### Description Removes a specified overlay object from the map. ### Method DELETE ### Endpoint /maps/overlays/{overlayId} ### Parameters #### Path Parameters - **overlayId** (string) - Required - The unique identifier of the overlay to remove. ### Request Example ``` DELETE /maps/overlays/overlay_12345 ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the overlay has been removed. #### Response Example ```json { "message": "Overlay overlay_12345 removed successfully." } ``` ``` -------------------------------- ### void view.animate(options, callback) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Applies an animation to the View control's content. A callback function can be provided to be executed once the animation is complete. Note that the view might change visually after animation and can be restored using the `restore` method. ```APIDOC ## void view.animate(options, callback) ### Description Applies an animation to the View control's content. A callback function can be provided to be executed once the animation is complete. Note that the view might change visually after animation and can be restored using the `restore` method. After the animation ends, the View is still displayed and may need to be explicitly closed using the `clear` method. ### Method `POST` (instance method) ### Endpoint `view.animate` ### Parameters #### Path Parameters - **options** (ViewAnimationOptions) - Optional - Configuration object for the animation (e.g., type, duration). - **callback** (NativeObjSuccessCallback) - Optional - A function to be called when the animation completes. ### Request Example ```javascript view.animate({ type: 'fade-in', duration: '1s' }, function() { console.log('Animation complete!'); }); ``` ### Response #### Success Response (200) - **void** - This method does not return a value. ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Create and Add a Map Circle Source: https://www.dcloud.io/docs/api/zh_cn/maps Illustrates the creation of a circular overlay on a map. This involves specifying the center coordinates and radius, and then adding the circle object to the map. ```javascript var circleObj = new plus.maps.Circle(new plus.maps.Point(116.347496, 39.970191), 500); map.addOverlay(circleObj); ``` -------------------------------- ### View getViewById(id) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Retrieves a View control object by its unique identifier. If multiple views share the same ID, the first one created is returned. Returns null if no view with the specified ID is found. ```APIDOC ## View plus.nativeObj.View.getViewById(id) ### Description Retrieves a View control object by its unique identifier. If multiple views share the same ID, the first one created is returned. Returns null if no view with the specified ID is found. ### Method `GET` (static method) ### Endpoint `plus.nativeObj.View.getViewById` ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the View control to find. ### Response #### Success Response (View) - **View** (View) - The View control object if found, otherwise null. ### Request Example ```javascript var view = plus.nativeObj.View.getViewById('test'); if (view) { console.log("Found View with ID 'test'"); } else { console.log("View with ID 'test' not found, please create it first."); } ``` ### Response Example ```json { "status": "success", "data": { "viewId": "test" } } ``` ``` -------------------------------- ### Update View Styles with setStyle (JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Dynamically updates the style of a View control. It accepts a ViewStyles object to modify properties like position and size. This method does not return any value. ```javascript void view.setStyle(styles); // Example: // view.setStyle({top:'0px',left:'0px',height:'50%',width:'100%'}); ``` -------------------------------- ### Define Position Interface (TypeScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Defines the Position interface, which specifies the properties for defining the location and dimensions of UI elements. It includes attributes for top, left, width, height, bottom, and right offsets. ```typescript interface Position { attribute String top; attribute String left; attribute String width; attribute String height; attribute String bottom; attribute String right; } ``` -------------------------------- ### Load Bubble Content from Image Path Source: https://www.dcloud.io/docs/api/zh_cn/maps Shows how to set the content of a map bubble by loading an image from a specified path. This method replaces any existing icon or text content with the loaded image. ```javascript void bubObj.loadImage( path ); ``` -------------------------------- ### Define RichTextStyles Interface (TypeScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Defines the structure for rich text styling, including alignment, font family, and font source path. This interface is used to configure the appearance of rich text elements. ```typescript interface RichTextStyles{ attribute String align; attribute String family; attribute String fontSrc; } ``` -------------------------------- ### Get Directory Remote URL Source: https://www.dcloud.io/docs/api/zh_cn/io Retrieves the network URL path for a directory entry, typically starting with "http://localhost:13131/". Returns a DOMString representing the network URL. Supports Android 2.2+ and iOS 4.3+. ```javascript DOMString entry.toRemoteURL(); ``` -------------------------------- ### Cross-Origin HTTP Requests with DCloud XMLHttpRequest API (JavaScript) Source: https://context7.com/context7/dcloud_io/llms.txt Shows how to perform cross-origin HTTP requests using the DCloud XMLHttpRequest API. It includes examples for GET and POST requests, handling status changes, monitoring progress, setting timeouts, and aborting requests. This API provides a complete event callback mechanism. ```javascript document.addEventListener('plusready', function(){ // 创建XMLHttpRequest对象 var xhr = new plus.net.XMLHttpRequest(); // 监听状态变化 xhr.onreadystatechange = function () { console.log("readyState: " + xhr.readyState); if (xhr.readyState == 4) { if (xhr.status == 200) { console.log("请求成功: " + xhr.responseText); var data = JSON.parse(xhr.responseText); // 处理返回的JSON数据 } else { console.log("请求失败: " + xhr.status); } } } // 监听进度事件 xhr.onprogress = function(e) { if (e.lengthComputable) { var percentComplete = (e.loaded / e.total) * 100; console.log("下载进度: " + percentComplete + "%gotoxy"); } }; // GET请求 xhr.open("GET", "http://api.example.com/users"); xhr.send(); // POST请求示例 var xhr2 = new plus.net.XMLHttpRequest(); xhr2.onreadystatechange = function() { if (xhr2.readyState == 4 && xhr2.status == 200) { console.log("POST成功: " + xhr2.responseText); } }; xhr2.open("POST", "http://api.example.com/login"); xhr2.setRequestHeader('Content-Type', 'application/json'); var loginData = {username: 'user@example.com', password: '123456'}; xhr2.send(JSON.stringify(loginData)); // 设置超时和取消请求 xhr.timeout = 30000; // 30秒超时 xhr.ontimeout = function() { console.log("请求超时"); }; // xhr.abort(); // 取消请求 }, false); ``` -------------------------------- ### Create Native View with Rich Text using H5+ (JavaScript) Source: https://www.dcloud.io/docs/api/zh_cn/nativeobj Shows how to create a native view and draw rich text content onto it using the plus.nativeObj.View and drawText methods. It demonstrates embedding HTML-like tags for text formatting, links, and images, with custom font settings. ```javascript NativeObj Example
``` -------------------------------- ### DCloud CacheClearCallback Example Source: https://www.dcloud.io/docs/api/zh_cn/cache This is an example of a callback function `CacheClearCallback` used with `plus.cache.clear`. It is triggered after the cache clearing operation is completed. This callback is supported on Android and iOS. ```javascript function onCompleted() { // Clear cache completed code. } ``` -------------------------------- ### DCloud CacheCalculateCallback Example Source: https://www.dcloud.io/docs/api/zh_cn/cache This is an example of a callback function `CacheCalculateCallback` used with `plus.cache.calculate`. It receives the calculated cache size in bytes upon completion of the calculation. This callback is supported on Android and iOS. ```javascript function onCompleted( size ) { // Calculate cache complete code. } ```