window[ "eval" ].call( window, data ); 语法错误

在IE浏览器中,JS代码会报错,解决办法是去掉JS代码里所写的注释。
在IE浏览器中js报这个错,其实只要将js中所写的注释去掉就可以了。
我更换调试从2.0变成1.0后,报错了: index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/history/history.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/history/history.js:81) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/edit/edit.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/edit/edit.js:177) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/add-product/add-product.js:7) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/add-product/add-product.js:506) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/top-product/top-product.js:7) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/top-product/top-product.js:196) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/new-collect/new-collect.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/new-collect/new-collect.js:174) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/new-history/new-history.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/new-history/new-history.js:153) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/loginWithCode/loginWithCode.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/loginWithCode/loginWithCode.js:147) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///store/index.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/loginWithPassWord/loginWithPassWord.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/loginWithPassWord/loginWithPassWord.js:67) at eval (<anonymous>) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/customer-service/customer-service.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/customer-service/customer-service.js:37) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/setting/setting.js:4) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/setting/setting.js:81) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/bind-info/bind-info.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/bind-info/bind-info.js:266) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/accountInfo/accountInfo.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/accountInfo/accountInfo.js:124) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 ReferenceError: wx is not defined at eval (weapp:///common/vendor.js:1926) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at n (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:4741) at eval (weapp:///pages/test2/test2.js:6) at C (eval at Ce.t.call.document (runtime.js:1), <anonymous>:3:5787) at eval (weapp:///pages/test2/test2.js:217) at eval (<anonymous>) at ye (index.js:1) at index.js:1 at ve (index.js:1) ye @ index.js:1 index.js:1 triggerBackgroundFetch {errMsg: "triggerBackgroundFetch:fail:token not set"}
09-07
//notation: js file can only use this kind of comments //since comments will cause error when use in webview.loadurl, //comments will be remove by java use regexp (function() { if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.inited) { return; } var receiveMessageQueue = []; var messageHandlers = {}; var sendMessageQueue = []; var responseCallbacks = {}; var persistentCallbacks = {}; var uniqueId = 1; var lastCallTime = 0; var stoId = null; var FETCH_QUEUE_INTERVAL = 20; var messagingIframe; var CUSTOM_PROTOCOL_SCHEME = "yy"; var QUEUE_HAS_MESSAGE = "__QUEUE_MESSAGE__"; // 创建消息index队列iframe function _createQueueReadyIframe() { messagingIframe = document.createElement('iframe'); messagingIframe.style.display = 'none'; messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; document.documentElement.appendChild(messagingIframe); } //创建消息体队列iframe function _createQueueReadyIframe4biz() { bizMessagingIframe = document.createElement('iframe'); bizMessagingIframe.style.display = 'none'; document.documentElement.appendChild(bizMessagingIframe); } //set default messageHandler 初始化默认的消息线程 function init(messageHandler) { console.log(222222222222222); if (WebViewJavascriptBridge._messageHandler) { throw new Error('WebViewJavascriptBridge.init called twice'); } _createQueueReadyIframe(); _createQueueReadyIframe4biz(); WebViewJavascriptBridge._messageHandler = messageHandler; var receivedMessages = receiveMessageQueue; receiveMessageQueue = null; for (var i = 0; i < receivedMessages.length; i++) { _dispatchMessageFromNative(receivedMessages[i]); } WebViewJavascriptBridge.inited = true; } // 发送 function send(data, responseCallback) { _doSend('send', data, responseCallback); } // 注册线程 往数组里面添加值 function registerHandler(handlerName, handler) { messageHandlers[handlerName] = handler; } function removeHandler(handlerName, handler) { delete messageHandlers[handlerName]; } // Register a persistent callback that won't be deleted after first use function registerPersistentCallback(callbackId, callback) { persistentCallbacks[callbackId] = callback; responseCallbacks[callbackId] = callback; } // Remove a persistent callback function removePersistentCallback(callbackId) { delete persistentCallbacks[callbackId]; delete responseCallbacks[callbackId]; } // 调用线程 function callHandler(handlerName, data, responseCallback, persistent) { // 如果方法不需要参数,只有回调函数,简化JS中的调用 console.log(11111111111); if (arguments.length == 2 && typeof data == 'function') { responseCallback = data; data = null; } _doSend(handlerName, data, responseCallback, persistent); } // Call handler with persistent callback that can be reused function callHandlerPersistent(handlerName, data, responseCallback) { if (arguments.length == 2 && typeof data == 'function') { responseCallback = data; data = null; } _doSend(handlerName, data, responseCallback, true); } //sendMessage add message, 触发native处理 sendMessage function _doSend(handlerName, message, responseCallback, persistent) { var callbackId; console.log(1); if(typeof responseCallback === 'string'){ console.log(2); callbackId = responseCallback; } else if (responseCallback) { console.log(3); callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime(); responseCallbacks[callbackId] = responseCallback; if (persistent) { persistentCallbacks[callbackId] = responseCallback; } message.callbackId = callbackId; }else{ console.log(4); callbackId = ''; } try { console.log(5); var fn = eval('WebViewJavascriptBridge.' + handlerName); } catch(e) { console.log(e); } if (typeof fn === 'function'){ console.log(6); var responseData = fn.call(WebViewJavascriptBridge, JSON.stringify(message), callbackId); if(responseData){ console.log(7); responseCallback = responseCallbacks[callbackId]; if (!responseCallback) { console.log(8); return; } responseCallback(responseData); // Only delete if it's not a persistent callback if (!persistentCallbacks[callbackId]) { console.log(9); delete responseCallbacks[callbackId]; } } } sendMessageQueue.push(message); messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; } // 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容 function _fetchQueue() { // 空数组直接返回 if (sendMessageQueue.length === 0) { return; } // _fetchQueue 的调用间隔过短,延迟调用 if (new Date().getTime() - lastCallTime < FETCH_QUEUE_INTERVAL) { if (!stoId) { stoId = setTimeout(_fetchQueue, FETCH_QUEUE_INTERVAL); } return; } lastCallTime = new Date().getTime(); stoId = null; var messageQueueString = JSON.stringify(sendMessageQueue); sendMessageQueue = []; //android can't read directly the return data, so we can reload iframe src to communicate with java bizMessagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString); } //提供给native使用, function _dispatchMessageFromNative(messageJSON) { setTimeout(function() { var message = JSON.parse(messageJSON); var responseCallback; //java call finished, now need to call js callback function if (message.responseId) { responseCallback = responseCallbacks[message.responseId]; if (!responseCallback) { return; } responseCallback(message.responseData); // Only delete if it's not a persistent callback if (!persistentCallbacks[message.responseId]) { delete responseCallbacks[message.responseId]; } } else { //直接发送 if (message.callbackId) { var callbackResponseId = message.callbackId; responseCallback = function(responseData) { _doSend('response', responseData, callbackResponseId); }; } var handler = WebViewJavascriptBridge._messageHandler; if (message.handlerName) { handler = messageHandlers[message.handlerName]; } //查找指定handler try { handler(message.data, responseCallback); } catch (exception) { if (typeof console != 'undefined') { console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception); } } } }); } //提供给native调用,receiveMessageQueue 在会在页面加载完后赋值为null,所以 function _handleMessageFromNative(messageJSON) { if (receiveMessageQueue) { receiveMessageQueue.push(messageJSON); } _dispatchMessageFromNative(messageJSON); } WebViewJavascriptBridge.init = init; WebViewJavascriptBridge.doSend = send; WebViewJavascriptBridge.registerHandler = registerHandler; WebViewJavascriptBridge.removeHandler = removeHandler; WebViewJavascriptBridge.callHandler = callHandler; WebViewJavascriptBridge.callHandlerPersistent = callHandlerPersistent; WebViewJavascriptBridge.registerPersistentCallback = registerPersistentCallback; WebViewJavascriptBridge.removePersistentCallback = removePersistentCallback; WebViewJavascriptBridge._handleMessageFromNative = _handleMessageFromNative; WebViewJavascriptBridge._fetchQueue = _fetchQueue; var readyEvent = document.createEvent('Events'); var jobs = window.WVJBCallbacks || []; readyEvent.initEvent('WebViewJavascriptBridgeReady'); readyEvent.bridge = WebViewJavascriptBridge; window.WVJBCallbacks = []; jobs.forEach(function (job) { job(WebViewJavascriptBridge) }); document.dispatchEvent(readyEvent); })(); public static void webViewLoadLocalJs(WebView view, String path){ String jsContent = assetFile2Str(view.getContext(), path); view.loadUrl("javascript:" + jsContent); } public static String assetFile2Str(Context c, String urlStr){ InputStream in = null; try{ in = c.getAssets().open(urlStr); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); String line = null; StringBuilder sb = new StringBuilder(); do { line = bufferedReader.readLine(); if (line != null && !line.matches("^\\s*\\/\\/.*")) { sb.append(line); } } while (line != null); bufferedReader.close(); in.close(); return sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if(in != null) { try { in.close(); } catch (IOException e) { } } } return null; }注入.js文件报 Uncaught ReferenceError: WebViewJavascriptBridge is not defined -- From line 1 of 发现错误: Uncaught ReferenceError: WebViewJavascriptBridge is not defined https://pv-mall.wuyang-honda.com/h5/#/ 1 6553 ReferenceError: WebViewJavascriptBridge is not defined -- From line 79 of https://pv-mall.wuyang-honda.com/h5/assets/index-EaCfmwlF.js Uncaught ReferenceError: WebViewJavascriptBridge is not defined -- From line 1 of https://pv-mall.wuyang-honda.com/h5/#/ [system] Location: https://pv-mall.wuyang-honda.com/h5/#/ -- From line 10 of https://pv-mall.wuyang-honda.com/h5/assets/vconsole.min-QVp8m_0m.js [system] Client: Android 12 -- From line 10 of https://pv-mall.wuyang-honda.com/h5/assets/vconsole.min-QVp8m_0m.js [system] UA: Mozilla/5.0 (Linux; Android 12; ALN-AL00 Build/HUAWEIALN-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.196 Mobile Safari/537.36 Honda_ANDROIDAPP -- From line 10 of https://pv-mall.wuyang-honda.com/h5/assets/vconsole.min-QVp8m_0m.js
07-04
import jax import jax.numpy as jnp from flax import linen as nn from flax.training import train_state from flax import struct import optax import tensorflow_datasets as tfds import numpy as np import tensorflow as tf # 1. 数据预处理 def preprocess(image, label): image = tf.image.resize(image, [32, 32]) # Resize to 32x32 image = tf.cast(image, tf.float32) / 255.0 # [0, 1] image = (image - 0.5) / 0.5 # Normalize to [-1, 1] return image, label # 2. 加载数据集 def get_datasets(): train_ds, test_ds = tfds.load( "cifar10", split=["train", "test"], as_supervised=True, shuffle_files=True, data_dir="./data" ) train_ds = train_ds.map(preprocess).shuffle(10000).batch(128).prefetch(tf.data.AUTOTUNE) test_ds = test_ds.map(preprocess).batch(128).prefetch(tf.data.AUTOTUNE) return train_ds, test_ds # 3. 模型定义 - 简化版本,先去掉BatchNorm避免batch_stats问题 class ImprovedCNN(nn.Module): @nn.compact def __call__(self, x, training: bool = False): # 第一层卷积 x = nn.Conv(features=64, kernel_size=(3, 3), padding='SAME')(x) x = nn.relu(x) x = nn.max_pool(x, window_shape=(2, 2), strides=(2, 2)) # 第二层卷积 x = nn.Conv(features=128, kernel_size=(3, 3), padding='SAME')(x) x = nn.relu(x) x = nn.max_pool(x, window_shape=(2, 2), strides=(2, 2)) # 第三层卷积 x = nn.Conv(features=256, kernel_size=(3, 3), padding='SAME')(x) x = nn.relu(x) x = nn.max_pool(x, window_shape=(2, 2), strides=(2, 2)) # 全局平均池化 x = jnp.mean(x, axis=(1, 2)) # 全连接层 x = nn.Dense(features=512)(x) x = nn.relu(x) x = nn.Dropout(rate=0.3, deterministic=not training)(x) # 输出层 x = nn.Dense(features=10)(x) return x # 自定义训练状态(已修正缩进) @struct.dataclass class CustomTrainState(train_state.TrainState): dropout_rng: jax.Array # 4. 损失函数 & 准确率(修正拼写错误) def cross_entropy_loss(logits, labels): one_hot_labels = jax.nn.one_hot(labels, num_classes=10) # 修正:one_hot 不是 one_nort return optax.softmax_cross_entropy(logits, one_hot_labels).mean() def compute_accuracy(logits, labels): return jnp.mean(jnp.argmax(logits, axis=-1) == labels) # 5. 训练状态初始化(修正拼写+语法错误) def create_train_state(rng, learning_rate=0.01): model = ImprovedCNN() dummy_input = jnp.ones((1, 32, 32, 3), dtype=jnp.float32) # 修正:float32 不是 flogts2 rng, params_rng = jax.random.split(rng) rng, dropout_rng = jax.random.split(rng)# 初始化参数 variables = model.init(params_rng, dummy_input, training=False) params = variables['params'] # 使用学习率预热 + 余弦衰减(修正语法:补充分号) warmup_steps = 500 total_steps = 5000 schedule = optax.join_schedules( [ optax.linear_schedule( init_value=0.0, end_value=learning_rate, transition_steps=warmup_steps ), optax.cosine_decay_schedule( init_value=learning_rate, decay_steps=total_steps - warmup_steps ) ], boundaries=[warmup_steps] ) tx = optax.adamw(learning_rate=schedule, weight_decay=1e-4) # 修正:adamw 不是 edem return CustomTrainState.create( apply_fn=model.apply, params=params, tx=tx, dropout_rng=dropout_rng ) # 6. 训练和评估 Step (JIT编译) @jax.jit def train_step(state, batch): def loss_fn(params): # 为每次前向传播拆分新的 RNG dropout_rng, new_dropout_rng = jax.random.split(state.dropout_rng) # 使用 rngs 参数传递 dropout RNG logits = state.apply_fn( {'params': params}, batch[0], training=True, rngs={'dropout': dropout_rng} ) loss = cross_entropy_loss(logits, batch[1]) return loss, (logits, new_dropout_rng) grad_fn = jax.value_and_grad(loss_fn, has_aux=True) (loss, (logits, new_dropout_rng)), grads = grad_fn(state.params) state = state.apply_gradients(grads=grads) # 更新 dropout_rng state = state.replace(dropout_rng=new_dropout_rng) accuracy = compute_accuracy(logits, batch[1]) return state, loss, accuracy @jax.jit def eval_step(state, batch): # 评估时不需要 dropout logits = state.apply_fn({'params': state.params}, batch[0], training=False) loss = cross_entropy_loss(logits, batch[1]) accuracy = compute_accuracy(logits, batch[1]) return loss, accuracy # 7. 主训练循环 def main(): rng = jax.random.PRNGKey(42) rng, init_rng = jax.random.split(rng) train_ds, test_ds = get_datasets() state = create_train_state(init_rng) num_epochs = 10 for epoch in range(num_epochs): # Train train_losses, train_accuracies = [], [] for batch in tfds.as_numpy(train_ds): state, loss, acc = train_step(state, batch) train_losses.append(loss) train_accuracies.append(acc) avg_loss = np.mean(train_losses) avg_acc = np.mean(train_accuracies) print(f"Epoch {epoch + 1}/{num_epochs}, Loss: {avg_loss:.4f}, Train Acc: {avg_acc:.4f}") # Eval test_losses, test_accuracies = [], [] for batch in tfds.as_numpy(test_ds): loss, acc = eval_step(state, batch) test_losses.append(loss) test_accuracies.append(acc) test_acc = np.mean(test_accuracies) print(f"Test Accuracy: {test_acc:.4f}") print("Training completed!") # 8. 运行 if __name__ == "__main__": main() 把第1次训练的训练准确率提高到50%以上。把优化了的代码给我。
最新发布
11-02
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值